remove objects that touch an image borders

I’m new in opencv but I can’t find any methods to remove objects that touch an image borders. I have found only this old opencv page: https://answers.opencv.org/question/223554/how-to-remove-the-element-attached-to-the-image-border/ but I don’t know how to do this. So the question is – how can I remove objects that touch image’s borders in binary mode? Thanks!

Answer

You can iterate over pixels that touch borders and use floodFill method to them. Like this:

def reject_borders(image_):
    out_image = image_.copy()
    h, w = image_.shape[:2]
    for row in range(h):
        if out_image[row, 0] == 255:
            cv2.floodFill(out_image, None, (0, row), 0)
        if out_image[row, w - 1] == 255:
            cv2.floodFill(out_image, None, (w - 1, row), 0)
    for col in range(w):
        if out_image[0, col] == 255:
            cv2.floodFill(out_image, None, (col, 0), 0)
        if out_image[h - 1, col] == 255:
            cv2.floodFill(out_image, None, (col, h - 1), 0)
    return out_image

Leave a Reply

Your email address will not be published. Required fields are marked *