Python OpenCV2 图像裁剪:去除白色边框并扩展至原图尺寸
import cv2
读入图像
img = cv2.imread('example.jpg')
转为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
二值化处理
_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
计算边框大小
border_size = 0 for i in range(thresh.shape[0]): if thresh[i, 0] == 255: border_size += 1 for i in range(thresh.shape[0]): if thresh[i, thresh.shape[1]-1] == 255: border_size += 1 for i in range(thresh.shape[1]): if thresh[0, i] == 255: border_size += 1 for i in range(thresh.shape[1]): if thresh[thresh.shape[0]-1, i] == 255: border_size += 1
裁剪掉白色部分
crop_img = img[border_size:img.shape[0]-border_size, border_size:img.shape[1]-border_size]
扩展为原图一致大小的分辨率
resized_img = cv2.resize(crop_img, (img.shape[1], img.shape[0]))
保存图像
cv2.imwrite('result.jpg', resized_img)
原文地址: https://www.cveoy.top/t/topic/oYnH 著作权归作者所有。请勿转载和采集!