我正在扫描一堆套着保护套的棒球卡。我想只裁剪卡片或稍微裁剪卡片的边缘。过去几年我一直在使用 Python,并且想要一些指导如何最好地做到这一点。这是示例图像。
我审阅了一些有关 OpenCV 和 Pillow 的文章,但没有一篇足够相似以提供帮助。
您还没有说是否要包含蓝色边框或仅包含蓝色边框内的卡片。这是在 Python/OpenCV 中执行后者的一种方法。
输入:
import cv2
import numpy as np
# read the input image
img = cv2.imread('baseball_card.jpg')
# threshold on white
lower = (210,210,210)
upper = (235,235,235)
thresh = cv2.inRange(img, lower, upper)
# apply morphology
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5,5))
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (7,7))
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
# get largest contour
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
# get rotated rectangle
rotrect = cv2.minAreaRect(big_contour)
(center), (width,height), angle = rotrect
box = cv2.boxPoints(rotrect)
boxpts = np.intp(box)
# draw rotated rectangle on copy of image
rotrect_img = img.copy()
cv2.drawContours(rotrect_img,[boxpts],0,(0,0,255),2)
# create mask
mask = np.zeros_like(img, dtype=np.uint8)
cv2.drawContours(mask,[boxpts],0,(255,255,255),-1)
# apply mask to input
result = cv2.bitwise_and(img, mask)
# save images
cv2.imwrite('baseball_card_thresh.jpg', thresh)
cv2.imwrite('baseball_card_morph.jpg', morph)
cv2.imwrite('baseball_card_rot_rect.jpg', rotrect_img)
cv2.imwrite('baseball_card_mask.jpg', mask)
cv2.imwrite('baseball_card_result.jpg', result)
# show results
cv2.imshow('thresh', thresh)
cv2.imshow('morph', morph)
cv2.imshow('rotated rectangle', rotrect_img)
cv2.imshow('mask', mask)
cv2.imshow('result', result)
cv2.waitKey(0)
阈值图像:
形态学清理图像:
旋转矩形图像:
遮罩图像:
结果图: