使用OpenCV和Python可以在各种颜色的背景中找到文档边缘,实现在各种背景下扫描文档的功能。下面是一种可能的实现方法:
import cv2
import numpy as np
image = cv2.imread('your_image.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150)
contours, _ = cv2.findContours(edges.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
doc_contour = None
for contour in contours:
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
if len(approx) == 4:
doc_contour = approx
break
if doc_contour is not None:
cv2.drawContours(image, [doc_contour], -1, (0, 255, 0), 2)
rect = np.zeros((4, 2), dtype="float32")
s = doc_contour.sum(axis=1)
rect[0] = doc_contour[np.argmin(s)]
rect[2] = doc_contour[np.argmax(s)]
diff = np.diff(doc_contour, axis=1)
rect[1] = doc_contour[np.argmin(diff)]
rect[3] = doc_contour[np.argmax(diff)]
(tl, tr, br, bl) = rect
widthA = np.sqrt(((br[0] - bl[0]) ** 2) + ((br[1] - bl[1]) ** 2))
widthB = np.sqrt(((tr[0] - tl[0]) ** 2) + ((tr[1] - tl[1]) ** 2))
maxWidth = max(int(widthA), int(widthB))
heightA = np.sqrt(((tr[0] - br[0]) ** 2) + ((tr[1] - br[1]) ** 2))
heightB = np.sqrt(((tl[0] - bl[0]) ** 2) + ((tl[1] - bl[1]) ** 2))
maxHeight = max(int(heightA), int(heightB))
dst = np.array([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype="float32")
M = cv2.getPerspectiveTransform(rect, dst)
warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
cv2.imshow("Scanned Document", warped)
cv2.waitKey(0)
cv2.destroyAllWindows()
这是一个基本的实现方法,可以根据具体需求进行调整和优化。在实际应用中,可以根据不同的背景颜色和光照条件进行参数调整,以获得更好的效果。
推荐的腾讯云相关产品:腾讯云图像处理(Image Processing)服务,该服务提供了丰富的图像处理功能和API,可以用于图像识别、图像增强、图像分割等任务。具体产品介绍和链接地址请参考:腾讯云图像处理。
领取专属 10元无门槛券
手把手带您无忧上云