python-3.xopencvroi

How to remove part of images around board - opencv


I am working with ROI and this center element is what I am looking for. But this part of image above I need to remove.

enter image description here

smooth= cv2.GaussianBlur(gray, (3, 3), cv2.BORDER_DEFAULT)
T, thresh = cv2.threshold(smooth, 32, 255, cv2.THRESH_BINARY)

#roi = cv2.selectROI(thresh)
#print(roi)#=(2, 176, 36, 31)
roi_cropped = thresh[176:(176+31),2:(2+36)]

#kernel = np.ones((3, 3), np.uint8)
#erode = cv2.erode(roi_cropped, kernel) 
#show(erode)

contours, hierarchy = cv2.findContours(image=roi_cropped, mode=cv2.RETR_TREE, method=cv2.CHAIN_APPROX_NONE)

image_copy = img.copy()
cv2.drawContours(image=image_copy[176:(176+31),2:(2+36)], contours=contours, contourIdx=-1, color=(0, 255, 0), thickness=1, lineType=cv2.LINE_AA)
show(image_copy)

Solution

  • It's simple. Check if the bounding box of a contour touches the edges of the picture.

    # have `contours` from `roi_cropped`
    
    (height, width) = roi_cropped.shape[:2]
    
    for c in contours:
        (x, y, w, h) = bbox = cv.boundingRect(c)
        touches_edges = (x == 0) or (y == 0) or (x+w == width) or (y+h == height)
        print(touches_edges, ":", bbox)
    

    You can figure out how to erase contours. There are multiple options:

    You probably don't even need to erase those blobs. Just ignore them.