使用 cv2.threshold() 函数绘制轮廓

draw contour with cv2.threshold() function

我正在测试 cv2.threshold() function in with different values but I get each time unexpected results. So this means simply I do not understand the effect of the parameter:

有人可以解决这个问题吗?

比如我想按照白色画出这颗星星的轮廓:

这是我得到的:

来自这段代码:

import cv2    
im=cv2.imread('image.jpg') # read picture

imgray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) # BGR to grayscale

ret,thresh=cv2.threshold(imgray,200,255,cv2.THRESH_BINARY_INV)

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


cv2.drawContours(im,countours,-1,(0,255,0),3)
cv2.imshow("Contour",im)

cv2.waitKey(0)
cv2.destroyAllWindows()

每次我更改 maxval 的值时,我都会得到一个我无法理解的奇怪结果。那么如何使用这个函数正确地画出这颗星星的轮廓呢?

提前致谢。

您可能想尝试一张非常简单的图像,让您清楚地了解各种参数。下面所附图片的有趣之处在于,图片中显示的数字的灰度值等于该数字。例如。 200 是用灰度值 200 写的。这是您可以使用的示例 python 代码。

import cv2

# Read image
src = cv2.imread("threshold.png", cv2.CV_LOAD_IMAGE_GRAYSCALE)

# Set threshold and maxValue
thresh = 127
maxValue = 255

# Basic threshold example
th, dst = cv2.threshold(src, thresh, maxValue, cv2.THRESH_BINARY);

# Find Contours 
countours,hierarchy=cv2.findContours(dst,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

# Draw Contour
cv2.drawContours(dst,countours,-1,(255,255,255),3)

cv2.imshow("Contour",dst)
cv2.waitKey(0)

我从我最近写的 OpenCV Threshold Tutorial 中复制了以下图片。它通过示例图像、Python 和 C++ 代码解释了各种参数。希望这可以帮助。

输入图像

结果图片

为了更准确地找到轮廓,可以在图像上应用阈值,因为二值图像往往会提供更高的准确度,然后使用轮廓 method.Hope 这将有所帮助..!!!

这里你可以使用COLOR_BGR2HSV然后选择一种颜色,轮廓的制作会很容易尝试并告诉我 在黑色和转换时,你有相同的黄色和白色颜色,这就是为什么这不起作用