Python OpenCV2 图像裁剪:去除白色边框
以下是基于 Python 的 OpenCV2 代码示例,可以计算图像四周的白色边框大小,并裁剪掉白色部分,将剩余部分图像另存为新图片,新图片大小和原图一致。
import cv2
# 读取图片
img = cv2.imread('input.jpg', cv2.IMREAD_UNCHANGED)
# 计算边框大小
top = 0
bottom = 0
left = 0
right = 0
while cv2.mean(img[top])[0] == 255:
top += 1
while cv2.mean(img[img.shape[0] - bottom - 1])[0] == 255:
bottom += 1
while cv2.mean(img[:, left])[0] == 255:
left += 1
while cv2.mean(img[:, img.shape[1] - right - 1])[0] == 255:
right += 1
# 裁剪图片
croped = img[top:img.shape[0] - bottom, left:img.shape[1] - right]
# 保存图片
cv2.imwrite('output.jpg', cropped)
说明:
-
首先使用
cv2.imread()函数读取图片,cv2.IMREAD_UNCHANGED参数表示原始图像按照它们的原始深度读取。 -
使用
cv2.mean()函数计算边框的颜色值,如果颜色值是255,说明是白色。 -
使用
while循环计算边框大小,分别计算上、下、左、右四个方向的边框大小。 -
使用切片操作裁剪图片,
img[top:img.shape[0] - bottom, left:img.shape[1] - right]表示从第top行开始,到第(img.shape[0] - bottom)行结束,从第left列开始,到第(img.shape[1] - right)列结束。 -
使用
cv2.imwrite()函数将裁剪后的图片保存为新图片。
原文地址: https://www.cveoy.top/t/topic/oYny 著作权归作者所有。请勿转载和采集!