首页 > 解决方案 > Python OpenCV:从图像中删除边框

问题描述

假设我有这样的图像:

在此处输入图像描述

我想删除边框并得到这个:

在此处输入图像描述

所以完全相同的图像,没有边框。

我找到了一种“hacky”方法来找到外部轮廓并在其上画一条线......老实说这不是最好的方法,因为我需要调整线条的“粗细”,使其足够粗覆盖边界,但不要太厚,这样它就不会覆盖任何圆圈。

image变量是您在上面看到的图像(已经灰度化、阈值化)。

cnts = cv2.findContours(image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
cv2.drawContours(image, cnts, -1, 0, 15) # 15 is the right thickness for this image, but might not be for other ones...

结果是上面的第二张图。效果很好,但不适用于所有图像(因为厚度不同)。有一个更好的方法吗?

标签: pythonopencv

解决方案


这就是我在评论中的意思......填充所有像左上角一样的黑色,并用白色连接到它,这样你想要的位现在完全被白色包围到边缘。然后用黑色填充所有白色并连接到左上角的东西。

#!/usr/local/bin/python3

import numpy as np
import cv2
from PIL import Image

# Load image and greyscale it
im = np.array(Image.open("framedcircles.jpg").convert('L'))

# Normalize and threshold image
im = cv2.normalize(im, None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX)
res, im = cv2.threshold(im, 64, 255, cv2.THRESH_BINARY)

# Fill everything that is the same colour (black) as top-left corner with white
cv2.floodFill(im, None, (0,0), 255)

# Fill everything that is the same colour (white) as top-left corner with black
cv2.floodFill(im, None, (0,0), 0)

# Save result
Image.fromarray(im).save("result.png")

结果:

在此处输入图像描述


推荐阅读