【发布时间】:2014-01-30 07:13:55
【问题描述】:
我正在使用 python opencv2 在图像中找到最大的 blob。虽然我将 Image1 作为输入,但它会给出正确的输出,但当我尝试使用另一个图像 Image2 时,相同的代码会给出错误的输出。两个输入图像给出不同的阈值图像作为输出。我希望问题就在这里。其实我在做什么错误?提前致谢。
输入图片截图:-
http://www.4shared.com/download/oV1dy6YKba/image-00001.png
输出图片截图:-
http://www.4shared.com/download/R5fWf_nWba/1_online.png
红色矩形标记的对象是目标。 Image1 正确检测到对象,但 Image2 错误检测。
代码:-
import cv2
import numpy as np
def do(im):
im1 = im
im = cv2.cvtColor(im,cv2.COLOR_RGB2GRAY)
cv2.imwrite('01gray.jpg',im)
ret,thresh = cv2.threshold(im,127,255,0)
cv2.imwrite('02thresh.jpg',thresh)
contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(im1,contours,-1,(0,255,0),3)
cv2.imshow('test',im1)
cv2.imwrite('03test.png',im1)
#test
max_area = 0
best_cnt = None
for cnt in contours:
area = cv2.contourArea(cnt)
if area > max_area:
max_area = area
best_cnt = cnt
#print best_cnt
# finding centroids of best_cnt and draw a circle there
M = cv2.moments(best_cnt)
cx,cy = int(M['m10']/M['m00']), int(M['m01']/M['m00'])
print cx,cy
if best_cnt is not None:
x,y,w,h = cv2.boundingRect(best_cnt)
cv2.rectangle(im1, (x,y),(x+w,y+h), (0,0,255), 3)
cv2.imwrite('04test1.png',im1)
im = cv2.imread('Image1.jpeg') #Works good
#im = cv2.imread('Image2.png') #Problem with that Image
do(im);
【问题讨论】:
-
定义“正确的输出”。这很可能是阈值的问题,所以请添加一些阈值图像。
-
我无法放置所有图片,因为这个网站说“你需要更多的声誉”。所以,我只是更新了它的截图。请帮忙。谢谢...
标签: python image opencv contour