如何将基于OpenCV与Pytesseract的卡片扫描项目转为Python模块?
Hey there! Converting your existing card scanning Flask app into a reusable Python module is totally doable—let’s break this down step by step to make it straightforward.
Your current code mixes Flask web routing/request handling with the actual card scanning/OCR logic. First, we need to separate these two parts:
- Create a new file (e.g.,
card_scanner.py) to hold your core scanning functionality. - Move all image processing and OCR-related code into this file, wrapping it into reusable functions. For example:
import cv2 import pytesseract import os from PIL import Image import re BINARY_THRESHOLD = 180 def process_card_image(image_path): """Process card image and extract raw text via OCR""" # Read and resize image (match your original logic) ori_image = cv2.imread(image_path) resized_image = cv2.resize(ori_image, (984, 582)) # Optional: Add preprocessing (like binarization, noise reduction) here to improve OCR accuracy # Save processed image if needed (adjust path to be dynamic instead of hardcoded) processed_path = os.path.join(os.path.dirname(image_path), "processed_card.png") cv2.imwrite(processed_path, resized_image) # Extract text with pytesseract raw_text = pytesseract.image_to_string(Image.open(processed_path)) return raw_text def extract_structured_data(raw_text): """Parse raw OCR text into structured data (e.g., name, DOB) using regex""" structured_data = {} # Example: Extract date of birth (adjust regex to match your card format) dob_match = re.search(r"DOB:\s*(\d{2}/\d{2}/\d{4})", raw_text) if dob_match: structured_data["dob"] = dob_match.group(1) # Add more regex patterns for other fields (name, ID number, etc.) return structured_data - Move file handling logic (like saving uploaded files) into helper functions if you want the module to support file uploads directly.
Decide what functions you want to expose to users of your module. For example:
extract_card_data(image_path): Takes an image file path, returns structured card data as a dictionary.process_uploaded_file(file_obj): Handles uploaded file objects (useful if you later want to integrate this module back with a web framework).
If your module grows more complex, split it into multiple files for better organization:
card_scanner/ ├── __init__.py ├── image_processing.py # Image resizing, preprocessing ├── ocr_extraction.py # OCR text extraction and regex parsing └── utils.py # File handling, path utilities
In __init__.py, export your core functions so users can import them easily:
from .image_processing import process_card_image from .ocr_extraction import extract_structured_data __all__ = ["process_card_image", "extract_structured_data"]
If your module doesn’t need web functionality, remove all Flask-related code (routes, app instance, render_template, etc.). This keeps your module’s dependency list lean—only requiring opencv-python, pytesseract, and Pillow.
- Add docstrings to every function to explain what they do, their parameters, and return values (like the example in Step 1).
- Create an
example.pyfile to show how to use your module:from card_scanner import process_card_image, extract_structured_data # Example usage raw_text = process_card_image("my_card.png") card_data = extract_structured_data(raw_text) print("Extracted Card Data:", card_data)
- Test your module with different card images to ensure OCR accuracy and function reliability.
- Fix any hardcoded paths in your original code (like
C:/Users/shruthipriyanka/...)—replace them with dynamic paths usingos.pathutilities so the module works on any system.
A quick note: Your original code had a truncated line (cv2.imwrite("C:/Users/shruthipriyanka/PycharmProjects/Scanning/newone.png",ne...)—make sure to complete that logic before moving it into the module to avoid runtime errors.
内容的提问来源于stack exchange,提问作者Sruthipriyanga

