python - findContours 的输出是什么意思,我该如何解析它?

标签 python opencv

当使用 findContours() 函数时,我得到一个数组。我对数组中的数字的含义以及“dtype”是什么感到困惑。

代码:

contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))
print(contour)

输出:

([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))

我将如何解析这个数组以便稍后使用?我计划制作一个从包含图像数据的文件中读取指令的乌龟应用程序。我想知道如何将其转换为上述说明。

最佳答案

cv2.findConturs()

cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)     # Finding contours detection 

此方法返回两个值。轮廓和层次结构。 contours 是图像中所有轮廓的 Python 列表。每个单独的轮廓都是对象边界点的 (x,y) 坐标的 Numpy 数组。

在您的情况下,它返回相同的两个值,但不同之处在于您将其解析为字符串并将其放入单个变量中,这使得它难以理解。(阅读修复部分)

数据类型

每个 ndarray 都有一个关联的数据类型 (dtype) 对象。这个数据类型对象 (dtype) 告诉我们数组的布局。这意味着它为我们提供了以下信息:

  • 数据类型(整数、 float 、Python 对象等)
  • 数据大小(字节数)
  • 数据的字节顺序(小端或大端)
  • 如果数据类型是子数组,它的形状和数据类型是什么。

在你的情况下,它告诉 ndarray 中的数据是 int 类型以及数组维度

修复代码

在您的代码中,问题出在这部分:

contour = str(cv2.findContours(edges, cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE))

在此,您将 findCountours 返回的值解析为 str 类型。

cnt,heirarchy = cv2.findContours(edged_img,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)     # Finding contours detection 

编辑::

用于绘图

如果你想绘制所有检测到的轮廓,那么你必须使用 cv2.drawContours() 方法。

cv2.drawContours(image,contours,-1,(255,0,0),2)        # Drawing the detected contours on the image.

它需要 5 个值。它的第一个参数是源图像,第二个参数是应该作为 Python 列表传递的轮廓,第三个参数是轮廓的索引(在绘制单个轮廓时很有用。要绘制所有轮廓,传递 -1)和其余参数是颜色,厚度等。

如果你想看一个 python 程序,而不是拍摄图像并在其上绘制轮廓(信息),那么你可以查看这个开放源代码。

https://github.com/0xPrateek/ComputerVision-OpenCV3-Python/blob/master/contours%20detection.py

关于python - findContours 的输出是什么意思,我该如何解析它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56819426/

相关文章:

python - 二维数组的numpy 3d张量

python - 用于 OCR 的 OpenCv pytesseract

cvWatershed 不支持的格式或格式组合

python - 类型错误 : UMat() takes at most 2 arguments (3 given)

python - 矢量模块中的点积

python - 改进SQL INSERT查询以避免sql注入(inject)

c++ - 从 QT 资源加载 openCV Haar Cascade

c++ - 如何在 OpenCV 中使用高斯过滤单列垫

python - Eclipse 调试上的变量查看器截断字符串值

python - 将 QuadgramCollat​​ionFinder 转换为 PentagramCollat​​ionFinder