基于Django与Tesseract OCR的模糊低对比度图像文本提取问题
Django + Tesseract OCR 低质图像文本提取实现
项目场景
待处理图像特征:
- 模糊、低对比度
- 包含标题、日期、小号字体、加粗字体等多种文本块,部分文本模糊不清
- 图像尺寸约256×350像素,分辨率96 DPI
视图函数(views.py)
import os from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pytesseract import cv2 from PIL import Image import numpy as np import re # 设置Tesseract命令路径 pytesseract.pytesseract.tesseract_cmd = '/usr/bin/tesseract' def clean_text(text): # 清理常见OCR错误示例 text = re.sub(r'\s+', ' ', text) # 移除多余空白字符 text = re.sub(r'[^\w\s,.!?;:()"\\\']', '', text) # 保留常用标点符号 return text.strip() def home(request): return render(request, 'layout/index.html') def preprocess_image(image_path): # 读取图像 image = cv2.imread(image_path, cv2.IMREAD_COLOR) if image is None: raise ValueError(f"Error loading image: {image_path}") # 提取红色通道以提升对比度(可根据实际场景启用) red_channel = image[:, :, 2] # 转换为灰度图 gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 手动直方图拉伸提升对比度 min_val = np.min(gray) max_val = np.max(gray) stretched_gray = ((gray - min_val) / (max_val - min_val) * 255).astype(np.uint8) # 应用锐化蒙版改善模糊文本 blurred = cv2.GaussianBlur(stretched_gray, (9, 9), 10.0) unsharp_image = cv2.addWeighted(stretched_gray, 1.5, blurred, -0.5, 0) # 自适应阈值处理 binary = cv2.adaptiveThreshold(unsharp_image, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2) # 中值滤波去噪 denoised = cv2.medianBlur(binary, 3) return denoised def upload(request): if request.method == 'POST' and request.FILES.get('document'): document = request.FILES['document'] fs = FileSystemStorage() filename = fs.save(document.name, document) uploaded_file_url = fs.url(filename) # 预处理上传的图像 try: preprocessed_image = preprocess_image(fs.path(filename)) except ValueError as e: return render(request, 'layout/index.html', {'error': str(e)}) # 将处理后的图像转换为PIL格式 preprocessed_image_pil = Image.fromarray(preprocessed_image) # Tesseract提取文本,自定义配置 custom_config = r'--oem 3 --psm 12 --dpi 1500' text = pytesseract.image_to_string(preprocessed_image_pil, config=custom_config) # 清理提取的文本 text = clean_text(text) context = { 'uploaded_file_url': uploaded_file_url, 'text': text, } return render(request, 'layout/index.html', context) return render(request, 'layout/index.html')
HTML模板(layout/index.html)
<!DOCTYPE html> <html> <head> <title>文档文本提取</title> </head> <body> <h1>上传文档图像</h1> <form method="post" enctype="multipart/form-data" action="{% url 'upload' %}"> {% csrf_token %} <input type="file" name="document"> <button type="submit">上传并提取文本</button> </form> {% if uploaded_file_url %} <h2>已上传图像:</h2> <img src="{{ uploaded_file_url }}" alt="上传的文档图像"> <h2>提取的文本:</h2> <pre>{{ text }}</pre> {% endif %} </body> </html>
URL配置(urls.py)
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), path('upload/', views.upload, name='upload'), ]
内容的提问来源于stack exchange,提问作者Vishal Upadhyay
相关产品推荐
相关产品推荐

