我正在用Python学习OpenCV,并且我想学习如何计算图像中的对象/元素。
我写了一个用于计数的代码,但是得到了错误的结果。图片中有12个元素,而我得到40个元素,但是有些元素没有计算在内。
我不知道我在做什么错。
这是我的代码:
import cv2
img = cv2.imread('slika.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
print('There are 12 elements on this image')
#cv2.imshow('img', gray)
#cv2.waitKey(0)
ret,thresh = cv2.threshold(gray,127,255,1)
contours,h = cv2.findContours(thresh,1,1)
print('Number of elements found:', len(contours))
for cnt in contours:
cv2.drawContours(img,[cnt],0,(0,0,255),2)
cv2.imshow('img', img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
这是默认图像,包含12个元素:
结果如下:
您会看到无法识别粉色和两个黄色元素,但这是绿色元素的问题。
我在做什么错,以及如何解决?
有几点可以改进当前代码。
如果您实际查看gray
图像,则会发现的阈值127
太低。黄色和粉色结构的灰度值在上面127
,然后被省略cv2.threshold
。出于相同的原因,绿色结构也支离破碎。而且,通常,最好使用实际的枚举值之类的值cv2.THRESH_BINARY_INV
代替其数值。
为了更好地进行轮廓检测,最好使用cv2.RETR_EXTERNAL
检索模式,因此您只需考虑大多数外部轮廓。同样,使用枚举值。
通过这些更改,您的代码可以正常工作:
import cv2
# Read image
img = cv2.imread('DIVmd.jpg')
# Convert image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Show grayscale image
cv2.imshow('gray', gray)
print('There are 12 elements on this image')
# Inverse binary threshold image with threshold at 224,
# i.e. every pixel with value above 224 is set to 0,
# and every pixel with value below 224 is set to 1
_, thresh = cv2.threshold(gray, 224, 255, cv2.THRESH_BINARY_INV)
# Show thresholded image
cv2.imshow('thresh', thresh)
# Find contours
# cv2.RETR_EXTERNAL: retrieves only the extreme outer contours
# cv2.CHAIN_APPROX_NONE: stores absolutely all the contour points
contours, h = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
print('Number of elements found:', len(contours))
# Iterate all found contours
for cnt in contours:
# Draw contour in original/final image
cv2.drawContours(img, [cnt], 0, (0, 0, 255), 2)
# Show final image
cv2.imshow('img', img)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
出于可视化目的,这是您的gray
图像:
这是实际的阈值图像thresh
:
并且,最后输出img
:
当然,现在打印的输出也正确:
There are 12 elements on this image
Number of elements found: 12
Run Code Online (Sandbox Code Playgroud)
希望有帮助!
归档时间: |
|
查看次数: |
31 次 |
最近记录: |