我正在尝试使用轮廓检测图像的第二个极值点
我试着做下面的事情
代码如下:
import imutils
import cv2
import numpy as np
image = cv2.imread(r"SimpleBoxTest.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.threshold(gray, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)
cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnts = imutils.grab_contours(cnts)
c=sorted(cnts, key=cv2.contourArea)
c = np.delete(c, (-1), axis=0)
extLeft = tuple(c[c[:, :, 0].argmin()][0])
extRight = tuple(c[c[:, :, 0].argmax()][0])
extTop = tuple(c[c[:, :, 1].argmin()][0])
extBot = tuple(c[c[:, :, 1].argmax()][0])
下面是错误
Traceback (most recent call last):
File "C:/TestCode/DocumentLayoutDetection/extreamPoints.py", line 41, in <module>
extLeft = tuple(c[c[:, :, 0].argmin()][0])
IndexError: too many indices for array
变量c是数组的列表,因此添加一个for循环来迭代它。 这解决了错误:
您不需要删除最后一个元素,您可以从末尾获取第二个元素
c=sorted(cnts, key=cv2.contourArea)
的结果不是一个NumPy数组,而是一个列表您可以使用
type(c)
检查类型,结果是<class 'list'>
。您可以使用
del
:del c[-1]
删除最后一个元素,但不必这样做李>c = c[-2]
提取列表的最后一个元素。现在
type(c)
是<class 'numpy.ndarray'>
李>extLeft = c[:, :, 0].min()
和extRight = c[:, :, 0].max()
查找最小值和最大值李>代码如下:
更新:
如果需要找到的所有等高线中的第二个极值点,可以在
c
中迭代等高线:不使用for循环的解决方案:
np.vstack(c)
连接列表中的NumPy数组。然后找到连接数组中的极值点李>
代码:
结果:
相关问题 更多 >
编程相关推荐