python - 使用 findContours(cv2) 切片图像
问题描述
由于声誉问题,我无法发布图像,所以这里是我下载的图像的链接:
import cv2
import numpy as np
import matplotlib.pyplot as plt
image = cv2.imread(r'C:\Users\User\Desktop\shapes.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(gray, 200, 255, 0)
contours, hier = cv2.findContours(thresh, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
x,y,w,h = cv2.boundingRect(cnt)
shape = thresh[y:y+h,x:x+w]
plt.imshow(shape)
如图所示,它只返回一个轮廓而不是 6 个。
我究竟做错了什么 ?
解决方案
findContours()
在黑色背景上寻找白色物体,所以你需要这样的阈值:
ret, thresh = cv2.threshold(gray, 225, 255, cv2.THRESH_BINARY_INV)
你需要找到这样的轮廓:
im2, contours, hier = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
推荐阅读
- python - 正则表达式替换 Python
- java - 元素不可交互:元素大小为零
- c# - 表达式 - 是否有一种简单且“可视”的方式将它们组合成另一个表达式?
- javascript - 这个方法如何返回一个可以被调用者方法订阅的 Observable?
- c# - EF core 3.1 无法翻译 linq 查询
- node.js - Lambda (node) Express REST API with AWS API Gateway 502 Bad Gateway 错误
- ng-zorro-antd - ng-zorro-antd 模态不从父级继承提供者
- node.js - 按照教程制作一个不和谐的机器人,它可以工作
- javascript - 麻烦理解石头剪刀布程序的流程
- node.js - 我应该如何将随机数与这些值之一匹配?