OpenCV findContours()如果与黑白图像一起使用,则会出现投诉

2024-05-19 03:21:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用下面的代码执行边缘检测。但是我得到了一个错误,因为图像的颜色深度。我眼中的这个错误毫无意义,因为我将图像正确地转换为灰度图像,并在随后的步骤中转换为黑白图像,这肯定是正确的。当我调用findContours时,得到一个错误。

import cv2

def bw_scale(file_name, tresh_min, tresh_max):
    image = cv2.imread(file_name)
    image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    #(thresh, im_bw) = cv2.threshold(image, tresh_min, tresh_max, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    (thresh, im_bw) = cv2.threshold(image, tresh_min, tresh_max, 0)

    cv2.imwrite('bw_'+file_name, im_bw)
    return (thresh, im_bw)

def edge_detect(file_name, tresh_min, tresh_max):
    (thresh, im_bw) = bw_scale(file_name, tresh_min, tresh_max)
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


if __name__ == '__main__':
  edge_detect('test.jpg', 128, 255)

我得到这个错误:

dgrat@linux-v3pk:~> python aoi.py
OpenCV Error: Unsupported format or combination of formats ([Start]FindContours support only 8uC1 and 32sC1 images) in cvStartFindContours, file /home/abuild/rpmbuild/BUILD/opencv-2.4.9/modules/imgproc/src/contours.cpp, line 196
Traceback (most recent call last):
  File "aoi.py", line 25, in <module>
    edge_detect('test.jpg', 128, 255)
  File "aoi.py", line 19, in edge_detect
    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.error: /home/abuild/rpmbuild/BUILD/opencv-2.4.9/modules/imgproc/src/contours.cpp:196: error: (-210) [Start]FindContours support only 8uC1 and 32sC1 images in function cvStartFindContours

Tags: name图像image错误mincv2maxfile
2条回答

更新

考虑到已经将图像转换为灰度,问题应该出在通道范围上。FindContours仅支持32s8u。您可以使用^{}来确保得到类似uint8的结果。如果没有cv2.convertScaleAbs(image)should解决你的问题。

原始答案

正如错误中提到的FindContours support only 8uC1 and 32sC1 images。所以可能需要使用^{}之类的东西来将图像转换为支持的颜色空间。

代码中的问题是您误用了cv2.threshold()的返回值。

cv2.threshold返回2个参数:

  • 检索

    在使用OTSU方法进行阈值化时使用(返回最佳阈值),否则它将返回传递给函数的相同阈值,在您的情况下为128.0。

  • 夏令时

    是阈值结果图像

在您的代码中,thresh是一个浮点而不是Mat。

更改:

contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

编辑

下面使用以下测试映像查找原始代码的重构和简化版本。

enter image description here

import cv2

def edge_detect(file_name, tresh_min, tresh_max):
    image = cv2.imread(file_name)
    im_bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)

    (thresh, im_bw) = cv2.threshold(im_bw, tresh_min, tresh_max, 0)
    cv2.imwrite('bw_'+file_name, im_bw)

    contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    cv2.drawContours(image, contours, -1, (0,255,0), 3)
    cv2.imwrite('cnt_'+file_name, image)

if __name__ == '__main__':
  edge_detect('test.jpg', 128, 255)

这将生成以下bw_test.jpg

enter image description here

在cnt_test.jpg中突出显示以下轮廓

enter image description here

相关问题 更多 >

    热门问题