how to segment the connected area based on depth color in opencv

asked 2017-07-22 04:17:15 -0500

helxsz gravatar image

I have a picture like enter image description here, which i need to segment the picture into 8 blocks.

image description

I have tried this threshold method

img_gray = cv2.imread(input_file,cv2.IMREAD_GRAYSCALE) 
ret,thresh = cv2.threshold(img_gray,254,255,cv2.THRESH_BINARY)
kernel = np.array(cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3), (-1, -1)))

img_open = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel) cv2.imshow('abc',img_open) ret1,thresh1 = cv2.threshold(img_open,254,255,cv2.THRESH_BINARY_INV) contours, hierarchy = cv2.findContours(thresh1, cv2.RETR_CCOMP ,cv2.CHAIN_APPROX_NONE) for i in range(len(contours)): if len(contours[i]) > 20: x, y, w, h = cv2.boundingRect(contours[i]) cv2.rectangle(img, (x, y), (x+w, y+h), (0, 255, 0), 2) print (x, y),(x+w, y+h)

after the thresholding

image description

the end result is some blocks connected together are formed into a large segment, which is not what I hoped.

image description

Any other ways to get it around

edit retag flag offensive close merge delete

Comments

Canny should give you an answer

LBerger gravatar imageLBerger ( 2017-07-22 04:28:46 -0500 )edit
  • remember, that findContours expects white fg and black bg (you may need to invert the image
    • look at morphological ops, like erode/dilate to seperate the cars in the thresholded image
    • imho, you should try to seperate the gray and black cars before applying threshold. maybe using grabcut() based on their grayscale intensity
berak gravatar imageberak ( 2017-07-23 01:02:53 -0500 )edit