How to set a flexible threshold value?

asked 2017-11-03 10:01:00 -0500

shebna12 gravatar image
for c in contours0: #contours0 contains all the initial contours that includes noise
    [x, y, w, h] = cv2.boundingRect(c)
    current_area = w*h
    temp = temp + current_area
ave_area = temp/len(contours0)
threshold_area = (0.4 *(ave_area))
for c in contours0: 
    [x,y,w,h] = cv2.boundingRect(c)
    if ((w*h) >= threshold_area ):
        contours.append(c) #contours contains the final contours without noise contours

The code above finds the average area of contours0 and compares it later on to the threshold area. Anything lesser than the threshold area is not included in contours. But this doesn't work all the time. The main objective of the code is to delete unnecessary background noise from contours0.

There are other parts in my code that often needs manual fine tuning of the threshold value. They all differ when the size of the image is smaller/bigger.

edit retag flag offensive close merge delete

Comments

1

What do you mean by 'this doesn't work all the time'?

Does a set threshold work for contours in one image, but not another? If that's the case, have a look at otsu's method:

https://docs.opencv.org/trunk/d7/d4d/...

It's generally used for image thresholding, but you could put all your contour area values into a Mat and use it to find an appropriate threshold.

daveg2 gravatar imagedaveg2 ( 2017-11-03 10:46:12 -0500 )edit