使用该findContours()函数时我得到一个数组。我对数组中的数字的含义以及“dtype”是什么感到困惑。
代码:
contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))
print(contour)
Run Code Online (Sandbox Code Playgroud)
输出:
([array([[[21, 21]],
[[21, 90]],
[[90, 90]],
[[90, 21]]], dtype=int32), array([[[21, 22]],
[[22, 21]],
[[89, 21]],
[[90, 22]],
[[90, 89]],
[[89, 90]],
[[22, 90]],
[[21, 89]]], dtype=int32), array([[[23, 23]],
[[23, 88]],
[[88, 88]],
[[88, 23]]], dtype=int32), array([[[23, 24]],
[[24, 23]],
[[87, 23]],
[[88, 24]],
[[88, 87]],
[[87, 88]],
[[24, 88]],
[[23, 87]]], dtype=int32)], array([[[-1, -1, 1, -1],
[-1, -1, 2, 0],
[-1, -1, 3, 1],
[-1, -1, -1, 2]]], dtype=int32))
Run Code Online (Sandbox Code Playgroud)
我将如何解析这个数组以便稍后使用?我计划制作一个乌龟应用程序,从包含图像数据的文件中读取指令。我想知道如何将其转换为上述说明。
cv2.findConturs()
cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # Finding contours detection
Run Code Online (Sandbox Code Playgroud)
该方法返回两个值。轮廓和层次结构。轮廓是图像中所有轮廓的Python列表。每个单独的轮廓都是对象边界点的 (x,y) 坐标的 Numpy 数组。
在您的情况下,它返回相同的两个值,但不同之处在于您将其解析为字符串并将其放入单个变量中,这使得它很难理解。(阅读修复部分)
数据类型
每个 ndarray 都有一个关联的数据类型 (dtype) 对象。该数据类型对象 (dtype) 告诉我们数组的布局。这意味着它为我们提供了以下信息:
在你的例子中,它表明 ndarray 内的数据是 int 类型以及数组维度
修复你的代码
在您的代码中,问题出在这部分:
contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))
Run Code Online (Sandbox Code Playgroud)
在此,您将 findCountours 返回的值解析为 str 类型。
cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE) # Finding contours detection
Run Code Online (Sandbox Code Playgroud)
编辑 ::
用于绘图
如果你想绘制所有检测到的轮廓,那么你必须使用cv2.drawContours()方法。
cv2.drawContours(image,contours,-1,(255,0,0),2) # Drawing the detected contours on the image.
Run Code Online (Sandbox Code Playgroud)
它需要5价值观。它的第一个参数是源图像,第二个参数是应作为 Python 列表传递的轮廓,第三个参数是轮廓的索引(在绘制单个轮廓时很有用。要绘制所有轮廓,请传递 -1)和其余参数是颜色、厚度等。
如果你想看一个 python 程序,而不是获取图像并在其上绘制轮廓(信息),那么你可以检查这个开放源代码。
https://github.com/0xPrateek/ComputerVision-OpenCV3-Python/blob/master/contours%20detection.py