2

Hello I have an image with some beans and i need to draw the contours, problem is the edges overlap and lighting is not great so there are a lot of shadows that mess with the edge detection. beans

I've tried many combinations of filters with different parameters with no luck. This is my best setup so far (with very bad results):

  img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    
  bl = cv2.GaussianBlur(img_gray,(blur,blur),skew)
  b_thr = cv2.adaptiveThreshold(bl, 255, cv2.THRESH_BINARY_INV, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, thresh, c)
  er = cv2.erode(b_thr,np.ones((2,2)),iterations=e)
  mf = medianBlur(er,avg)
  contours, hierarchy = cv2.findContours(mf, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

median blur is to smooth out the edge and fill some gaps

filtered image

all parameters are controlled by trackbars. My main issue is that when i try to detect the edges I either lose precision in the light or dark areas or, if I set thresholding parameters too low, the shapes get all broken up. I even tried to use segmentation with no luck. I've looked into Hough Circles but I'm not sure it will be useful in my case.

I didn't get better results using sobel filter with and without canny edge detection, the only marginal improvement was using the saturation channel to "clean up" some of the grey background with a mask.

I've been playing with the parameters a lot but at this point I don't really know what to use

  • Tricky one. Have you tried using color ? You could try to extract the roughly red shapes first. It looks like all beans are all surrounded by black shadows, so you might also try to keep only that first. – Big Bro Apr 22 '22 at 09:41
  • yes you can try segmenting using color https://stackoverflow.com/questions/10948589/choosing-the-correct-upper-and-lower-hsv-boundaries-for-color-detection-withcv/ – Jeru Luke Apr 22 '22 at 10:18
  • thanks, segmenting red using the HSV colorspace did a great job! I used [the code from this answer](https://stackoverflow.com/questions/30331944/finding-red-color-in-image-using-python-opencv). Previously I tried the same thing with BGR without great success, now it's much better – beansdetection Apr 22 '22 at 10:47
  • tip: After segmenting color, if you have to find contours of each single bean, subtract your edge mask from the foreground mask. As in https://stackoverflow.com/questions/34650697/opencv-divide-contacted-circles-into-single/34653138#34653138 – Micka Apr 22 '22 at 11:03
  • @beansdetection did you figure out a solution? – Jeru Luke May 02 '22 at 21:17

0 Answers0