How to use OpenCV ConnectedComponents to get the images

17,534
image = cv2.imread('image.png', cv2.IMREAD_UNCHANGED);
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]

# getting mask with connectComponents
ret, labels = cv2.connectedComponents(binary)
for label in range(1,ret):
    mask = np.array(labels, dtype=np.uint8)
    mask[labels == label] = 255
    cv2.imshow('component',mask)
    cv2.waitKey(0)

# getting ROIs with findContours
contours = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
for cnt in contours:
    (x,y,w,h) = cv2.boundingRect(cnt)
    ROI = image[y:y+h,x:x+w]
    cv2.imshow('ROI', ROI)
    cv2.waitKey(0)

cv2.destroyAllWindows()
Share:
17,534

Related videos on Youtube

Chopin
Author by

Chopin

Updated on June 15, 2022

Comments

  • Chopin
    Chopin about 2 years

    How to use Python OpenCV ConnectedComponents function to obtain the images?

    From searching some past question, I have only been able to find how to shade the connected objects in different colors (Which I tested and it worked, but I have no idea how the labels work)
    Reference from these previously answered questions: Stackoverflow question 48303309 and Stackoverflow question 46441893

    Using this code, I can get the shaded output

    import cv2
    import numpy as np
    
    img = cv2.imread('eGaIy.jpg', 0)
    img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)[1]  # ensure binary
    ret, labels = cv2.connectedComponents(img)
    
    # Map component labels to hue val
    label_hue = np.uint8(179*labels/np.max(labels))
    blank_ch = 255*np.ones_like(label_hue)
    labeled_img = cv2.merge([label_hue, blank_ch, blank_ch])
    
    # cvt to BGR for display
    labeled_img = cv2.cvtColor(labeled_img, cv2.COLOR_HSV2BGR)
    
    # set bg label to black
    labeled_img[label_hue==0] = 0
    
    cv2.imshow('labeled.png', labeled_img)
    cv2.waitKey()
    

    Original Shaded

    Is there any way I can get the connected objects out from the image?
    So output would be multiple images from the original image

  • Chopin
    Chopin almost 6 years
    Thank you! It worked well. May I ask how to merge all the ROI into just 1 big ROI?
  • Chopin
    Chopin almost 6 years
    Should I keep the lowest x, highest x, lowest y, highest y during the contour loop, then crop out using image[ smally: highy - smally, smallx: highx - smallx]
  • jtlz2
    jtlz2 almost 5 years
    The first for loop can be very slow for a large image. Any ideas on how to accelerate it??
  • Scott
    Scott about 4 years
    You have to edit your answer: contours=cv2.findContours(...)[1] to contours=cv2.findContours(...)[0]