+
34
-

python如何擦去纸张照片上手写字迹?

python如何擦去纸张照片上手写字迹?


网友回复

+
22
-

处理黑色手写字迹的擦除方法

当试卷上的手写字迹是黑色的,与印刷文字颜色相同时,简单的颜色分割方法就不再适用了。这种情况下,我们需要采用更复杂的技术来区分和擦除手写字迹。以下是几种可行的方法:

1. 基于深度学习的图像修复

这是目前处理黑色手写字迹最有效的方法之一:

import cv2
import numpy as np
import torch
from lama_cleaner.model_manager import ModelManager
from lama_cleaner.schema import Config

def remove_black_handwriting_with_lama(image_path, mask_path, output_path):
    """
    使用LaMa深度学习模型擦除黑色手写字迹

    参数:
        image_path: 原始图像路径
        mask_path: 手写字迹掩码路径(需手动或半自动创建)
        output_path: 输出图像路径
    """
    # 读取图像和掩码
    img = cv2.imread(image_path)
    mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)

    # 初始化LaMa模型
    model = ModelManager(name="lama", device="cuda" if torch.cuda.is_available() else "cpu")

    # 设置配置
    config = Config(
        ldm_steps=25,
        ldm_sampler="plms",
        hd_strategy="Original",
        hd_strategy_crop_margin=32,
        hd_strategy_crop_trigger_size=2000,
        hd_strategy_resize_limit=2048,
    )

    # 执行修复
    result = model(img, mask, config)

    # 保存结果
    cv2.imwrite(output_path, result)
    print("处理完成,结果已保存到", output_path)

2. 结合OCR的半自动方法

这种方法尝试保护印刷文字,只修复其他区域:

import cv2
import numpy as np
import pytesseract
from PIL import Image

def remove_handwriting_with_ocr(image_path, output_path):
    """
    使用OCR识别印刷文字,然后尝试擦除非印刷文字区域
    """
    # 读取图像
    img = cv2.imread(image_path)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    # 二值化处理
    _, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

    # 使用OCR识别印刷文字区域
    # 注意:需要安装Tesseract OCR并设置路径
    pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # Windows路径示例

    # 获取OCR识别结果(包含边界框信息)
    ocr_results = pytesseract.image_to_data(Image.fromarray(gray), output_type=pytesseract.Output.DICT)

    # 创建掩码,初始全为255(白色)
    mask = np.ones_like(gray) * 255

    # 在掩码上标记OCR识别的文字区域为0(黑色)
    for i in range(len(ocr_results['text'])):
        # 只处理置信度高且非空的文本
        if int(ocr_results['conf'][i]) > 60 and ocr_results['text'][i].strip() != '':
            x = ocr_results['left'][i]
            y = ocr_results['top'][i]
            w = ocr_results['width'][i]
            h = ocr_results['height'][i]

            # 在掩码上将印刷文字区域标记为黑色(保护区域)
            cv2.rectangle(m...

点击查看剩余70%

我知道答案,我要回答