我有像下面这样带有边框的图像。我可以使用 OpenCV 或 python 去除图像中的这种边框吗?
我使用下面的代码进行裁剪,但是没有用。
copy = Image.fromarray(img_final_bin)
try:
bg = Image.new(copy.mode, copy.size, copy.getpixel((0, 0)))
except:
return None
diff = ImageChops.difference(copy, bg)
diff = ImageChops.add(diff, diff, 2.0, -100)
bbox = diff.getbbox()
if bbox:
return np.array(copy.crop(bbox))
最佳答案
这是一种使用阈值 + 轮廓过滤的方法。这个想法是通过阈值来获得二值图像。从这里我们找到轮廓并使用最大面积阈值进行过滤。我们将通过此过滤器的所有轮廓绘制到空白蒙版上,然后执行按位操作以删除边框。这是去除边框的结果
import cv2
import numpy as np
image = cv2.imread('1.png')
mask = np.zeros(image.shape, dtype=np.uint8)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area < 10000:
cv2.drawContours(mask, [c], -1, (255,255,255), -1)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
result = cv2.bitwise_and(image,image,mask=mask)
result[mask==0] = (255,255,255)
cv2.imwrite('result.png', result)
cv2.waitKey()
关于python - 使用 Python OpenCV 从图像中删除边框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58801994/