2

I have this image which is a result of subtracting two images. myinput

I want to get just the white block in the image which is marked in the image. I have tried a bit of morphological operations with help of this, this and some from my own previous work.

Unfortunately my code gives me not what I would like to have.

#new_diff result of subtraction
new_diff= np.array(new_diff, dtype= np.uint8)
kernel = np.ones((7,7), np.uint8)
erosion = cv2.erode(new_diff.copy(),kernel,iterations= 1)
median = cv2.medianBlur(erosion,3)
closing = cv2.morphologyEx(median, cv2.MORPH_CLOSE, np.ones((9,9),np.uint8),iterations=1)

cv2.imshow('closing', closing)

cnts =cv2.findContours(closing.copy(),cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)[0]

print 'no of cont',len(cnts)
areaArray = []
for i, c in enumerate(cnts):
    area = cv2.contourArea(c)
    areaArray.append(area)
#first sort the array by area
sorteddata = sorted(zip(areaArray, cnts), key=lambda x: x[0], reverse=True)
#find the nth largest contour [n-1][1]
c = sorteddata[0][1]

#print 'max contour=', c
cv2.drawContours(closing,[c],0,(255,255,255),3)
cv2.imshow('contours', closing)
cv2.waitKey(0)
cv2.destroyAllWindows()

The result after closing looks like this. closing result

But when I draw the biggest contour I end up with this. contour result

In some of the images, the part which I want is similar to that marked in the image but may be just half. Any idea how to make sure that the block is the biggest contour there is so that I can cut it out? Thanks in advance.

gaya
  • 463
  • 2
  • 6
  • 22
  • use median or morphological operations to remove noise. distance transform would also be an option. you should add a threshold operation to get rid of the low intensity all around your object. some preprocessing befor difference calculation might also help. crap in = crap out. – Piglet Aug 10 '17 at 19:09
  • @AlexanderReynolds I am using openCV 2.4 so it is the first return value. – gaya Aug 11 '17 at 08:49
  • @Piglet I would try out and see what I get! Thank you. – gaya Aug 11 '17 at 08:56

0 Answers0