【问题标题】:Python Opencv2 : Finding biggest blob in a image gives two different outputPython Opencv2:在图像中找到最大的斑点会给出两种不同的输出
【发布时间】: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


【解决方案1】:

您不应该对两张图像使用相同的阈值,因为该阈值将为您提供第一张图像中的斑点(白色)和第二张图像(不是飞机)中的背景(天空)的输出。

【讨论】:

    【解决方案2】:

    是的 Mr.Ted W。你是对的。

    现在,我正在使用 otsu 方法为每个输入图像找到阈值,如下所示

    (automatic_thresh_value_calc, im_bw) = cv2.threshold(input_gray_img, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)  
    ret,thresh = cv2.threshold(input_gray_img,automatic_thresh_value_calc,255,0)
    cv2.imwrite('thresholdedImage.jpg',input_gray_img)
    

    我说的对吗?否则,有没有在 python 中找到自动阈值的好方法?

    谢谢...

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-03
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多