如何填充与图像边界接触的轮廓?

2024-10-02 00:25:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有图像,我从一个亮度阈值上画轮廓,轮廓在这之后从内部填充。我遇到的问题是填充边界线

最新的尝试是在图像周围添加边框,并在轮廓填充后将其删除,但它并不适用于所有文件

显示问题的示例 [1] :https://imgur.com/a/XyOj0zC

我对解决这个问题的新方法持开放态度,提前谢谢你

    #open the image as a numpy array, in grayscale
    img_input = cv2.imread(input_folder + "\\" + filename, cv2.IMREAD_GRAYSCALE)

    #blur for more accurate contour detection
    img_blurred = cv2.GaussianBlur(img_input, (5,5), cv2.BORDER_DEFAULT)

    #contour selection with otsu's threshold
    image = cv2.threshold(img_blurred, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

    #border creation to fill border hitting contours
    row, col = image.shape[:2]
    bottom = image[row - 2:row, 0:col]
    mean = cv2.mean(bottom)[0]
    bordersize = 10
    image = cv2.copyMakeBorder(
        image,
        top=bordersize,
        bottom=bordersize,
        left=bordersize,
        right=bordersize,
        borderType=cv2.BORDER_CONSTANT,
        value=255
        )

    #border hole creation so the whole image doesnt get filled due to continous contour by the borders
    image[100:101,0:10] = [0]

    #filling the contours
    cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = cnts[0] if len(cnts) == 2 else cnts[1]
    cv2.fillPoly(image, cnts, [255, 255, 255])

    #removing the created borders
    y, x = image.shape
    final_img = image[10:y-10, 10:x-10]

    #saving the file
    cv2.imwrite(output_folder + "\\" + filename[:-4] + ".png", final_img)

Tags: the图像imageimginputfolderfilenamecv2

热门问题