Python Opencv2 : Finding biggest blob in a image gives two different output

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 :- Output Images Screenshot :- Red color rectangle marked object is Target. Image1 detected object correctly, but Image2 wrongly detects.


import cv2
import numpy as np

def do(im):
    im1 = im
    im = cv2.cvtColor(im,cv2.COLOR_RGB2GRAY)
    ret,thresh = cv2.threshold(im,127,255,0)
    contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

    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)

im = cv2.imread('Image1.jpeg') #Works good
#im = cv2.imread('Image2.png') #Problem with that Image


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

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)

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

Need Your Help

Sharepoint Document Upload Page - Passing URL Variables?

sharepoint upload field document-library

Throughout my SharePoint site, I have several document repositories that are tied to primary keys from an external database. I have added custom columns in the document library metadata fields so ...

jquery/css wrap text bottom up

javascript jquery html css text

I am trying to wrap text in a div using css and/or jQuery such that the bottom line is the longest.