程序员求职经验分享与学习资料整理平台

网站首页 > 文章精选 正文

使用python+opencv 实现拍摄文档照片一键清晰+裁剪+透视矫正

balukai 2025-01-01 17:57:08 文章精选 5 ℃

接上篇文章, 我做了透视矫正的功能,且实现裁剪,但是效果不是很理想,欢迎小伙伴来评论

import cv2
import numpy as np

def process_image(image, is_original=False):
    # 1. 复制图层并进行高斯模糊
    blurred = cv2.GaussianBlur(image, (201, 201), 0).astype(float)
    # 2. 实现“划分”模式
    epsilon = 1e-7
    divided = image / (blurred + epsilon)
    # 将结果缩放到0-255范围并转换为8位无符号整数
    divided = np.clip(divided * 255, 0, 255).astype(np.uint8)
    merged = divided.astype(float)  # 转换为浮点数以避免操作中的整数截断
    # 3. 实现正片叠底模式
    multiply = (divided * merged) / 255
    return np.clip(multiply, 0, 255).astype(np.uint8)

def scan_effect(image_path):
    # 读取原始图像
    original = cv2.imread(image_path)
    gray = cv2.cvtColor(original, cv2.COLOR_BGR2GRAY)
    # 边缘检测
    edged = cv2.Canny(gray, 50, 150)
    # 膨胀操作,增强轮廓
    dilated = cv2.dilate(edged, None, iterations=2)
    # 找到轮廓
    contours, _ = cv2.findContours(dilated, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
    contours = sorted(contours, key=cv2.contourArea, reverse=True)[:10]

    # 遍历轮廓,找到大概是文档的四边形
    screen_contour = None
    for contour in contours:
        peri = cv2.arcLength(contour, True)
        approx = cv2.approxPolyDP(contour, 0.01 * peri, True)
        if len(approx) == 4:
            screen_contour = approx
            break

    if screen_contour is not None:
        # 在原始图像上绘制轮廓
        # cv2.drawContours(original, [screen_contour], -1, (0, 255, 0), 2)
        # 透视变换
        def order_points(pts):
            if len(pts.shape) == 3:
                pts = pts.reshape(4, 2)
            rect = np.zeros((4, 2), dtype="float32")
            center = np.mean(pts, axis=0)
            for point in pts:
                if point[0] < center[0] and point[1] < center[1]:
                    rect[0] = point  # 左上
                elif point[0] > center[0] and point[1] < center[1]:
                    rect[1] = point  # 右上
                elif point[0] > center[0] and point[1] > center[1]:
                    rect[2] = point  # 右下
                else:
                    rect[3] = point  # 左下
            return rect

        def four_point_transform(image, pts):
            rect = order_points(pts)
            (tl, tr, br, bl) = rect
            widthA = np.linalg.norm(br - bl)
            widthB = np.linalg.norm(tr - tl)
            maxWidth = max(int(widthA), int(widthB))
            heightA = np.linalg.norm(tr - br)
            heightB = np.linalg.norm(tl - bl)
            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)
            return cv2.warpPerspective(image, M, (maxWidth, maxHeight))

        warped = four_point_transform(original, screen_contour.reshape(4, 2))
        multiply = process_image(warped)
    else:
        multiply = process_image(original, is_original=True)

    # 显示和保存最终结果
    cv2.imshow("Result", multiply)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    cv2.imwrite(r'C:\Users\40650\Desktop\20241009171353-1.jpg', multiply)

scan_effect(r'C:\Users\40650\Desktop\20241009171353.jpg')

但是透视矫正的功能好像不是很理想,有望改进

最近发表
标签列表