Question


I am finding biggest blob in a image using python opencv2. While I give Image1 as input it gives correct output but the same code gives wrong output when I try with another image Image2. The two input images gives different thresholded images as output. I hope problem is here. Actually what mistake I am doing? Thanks in advance.

Input Images Screenshot :-
http://www.4shared.com/download/oV1dy6YKba/image-00001.png
Output Images Screenshot :-
http://www.4shared.com/download/R5fWf_nWba/1_online.png

Red color rectangle marked object is Target. Image1 detected object correctly, but Image2 wrongly detects.

Code:-

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);
Was it helpful?

Solution

You should not use the same threshold for the two images, because the threshold will give you the output of the blobs (white) in the first image and the background (sky) in the second image (not the airplane).

OTHER TIPS

Yes Mr.Ted W. You are correct.

Now, I am finding threshold value for each input image using otsu method as follows

(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)

Am I correct ? Else, Is there are good way to find automatic threshold value in python ?

Thanks...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top