我无法检测这张图片中的轮廓
类图图片
我想检测图中的所有边界轮廓,但到目前为止我的程序只检测图像中显示的图像边界
忽略中间的0,表示是轮廓0。
我不确定问题出在我的代码中,因为它可以检测黑色背景图像中的轮廓。
filename = sys.argv[1]
t = int(sys.argv[2])
img = cv2.imread(filename)
resized = imutils.resize(img, width=300)
ratio = img.shape[0] / float(resized.shape[0])
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5,5), 0)
(t, binary) = cv2.threshold(blur, t, 255, cv2.THRESH_BINARY)
_ ,cnts, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for (i,c) in enumerate(cnts):
M = cv2.moments(c)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
else:
cX, cY = 0, 0
(x,y,w,h) = cv2.boundingRect(c)
area = cv2.contourArea(c)
cv2.rectangle(img, (x, y), (x + w, y + h),(0, 255, 255), 2)
print("Object %d has dimensions x=%d, y=%d, w=%d, h=%d area=%d" % (i,x,y,w,h,int(w*h)))
cv2.putText(img, str(i), (cX, cY),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 1)
最佳答案
I am note sure where the problem lies in my code as it can detect contours in images with a black background.
这几乎肯定是您的问题。来自OpenCV tutorial
In OpenCV, finding contours is like finding white object from black background. So remember, object to be found should be white and background should be black.
This SO Q/A向您展示如何反转图像。
正如所讨论的那样,您肯定需要检测黑底白字 here
关于python - 检测白色背景图像中的轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49924470/