裁剪图片的边框 python

crop the border of image python

我有这张照片

我想像这样裁剪它

我使用此代码,但它不会裁剪黑色边框。那么,有人可以帮助我吗?

    im = cv2.imread("Data/"+file, 0)
    retval, thresh_gray = cv2.threshold(im, thresh=100, maxval=255, type=cv2.THRESH_BINARY)
    points = np.argwhere(thresh_gray==0)
    points = np.fliplr(points)
    x, y, w, h = cv2.boundingRect(points)
    crop = im[y:y+h, x:x+w] # create a crop
    retval, thresh_crop = cv2.threshold(crop, thresh=200, maxval=255, type=cv2.THRESH_BINARY)
    path = 'D:\Picture\Camera Roll'
    cv2.imwrite(os.path.join(path , file),thresh_crop)

我认为您可以使用 contours 来解决问题 等高线是 curve/line 连接相同强度的连续点。因此,包含书面脚本的框是一个轮廓。图像中的轮廓也有关系,比如一个轮廓可以是其他轮廓的父级。在您的图像中,盒子可能是书面脚本的父级。

cv2.findContours 找到图像中的所有轮廓,第二个参数(cv2.RETR_TREE)是提及应该返回什么样的关系。由于轮廓具有层次结构,因此框很可能位于轮廓列表的索引 0 或 1 中。

import matplotlib.pyplot as plt
%matplotlib inline
img = cv2.imread('image.png', 0)
ret, thresh = cv2.threshold(img, 127, 255, 0)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

虽然第一个轮廓 (contours[0]) 代表框,但出于某种原因它是第二个。

img_copy = img.copy()
cnt= contours[1]
cv2.drawContours(img_copy, [cnt], -1, color = (255, 255, 255), thickness = 20)
plt.imshow(img_copy, 'gray')

有了轮廓后,只需在轮廓上画一条粗白线即可删除框。这是一个 在图像上绘制特定轮廓的方法

Don't worry about the bounding box in these images. It's just matplotlib. Your image is what is inside the coordinate box.