簡體   English   中英

如何在 Python 中使用 OpenCV 和 Tesseract 處理信用卡字體

[英]How to handle Credit Cards fonts with OpenCV and Tesseract in Python

我正在嘗試使用 OpenCV 讀取卡片並輸出卡號和有效期。

import cv2
import pytesseract

filename = 'image1.png'
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
canny = cv2.Canny(gray, 50, 150, apertureSize=3)
result = pytesseract.image_to_string(canny)
print(f"OCR Results: {result}")

cv2.imshow('img', img)
cv2.imshow('canny', canny)

if cv2.waitKey(0) & 0xff == 27:
    cv2.destroyAllWindows()

在此處輸入圖片說明

  1. 處理前的圖像

在此處輸入圖片說明

  1. Canny 之后的圖像

結果文本看起來不太好。 請看下面的截圖:

在此處輸入圖片說明

問題:如何正確處理卡片字體以獲得更好的效果。 任何想法都受到高度贊賞。

謝謝。

在傳遞文本邊緣時,OCR 似乎無法正常工作。
您最好應用閾值而不是使用 Canny。

我建議以下幾個階段:

  • 從BGR轉換到HSV色彩空間,得到HSV的S(飽和度)色彩通道。
    S 中的所有灰色像素均為零,彩色像素均高於零。
  • 使用自動閾值轉換為二進制(使用cv2.THRESH_OTSU )。
  • 用最大尺寸裁剪輪廓。
    因為您發布的圖片包含一些背景。
  • 在裁剪區域應用 OCR。

這是代碼:

import numpy as np
import cv2
import imutils  # https://pypi.org/project/imutils/
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r'C:\Program Files\Tesseract-OCR\tesseract.exe'  # I am using Windows

img = cv2.imread('image1.png')  # Read input image

# Convert from BGR to HSV color space
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Get the saturation color channel - all gray pixels are zero, and colored pixels are above zero.
s = hsv[:, :, 1]

# Convert to binary using automatic threshold (use cv2.THRESH_OTSU)
ret, thresh = cv2.threshold(s, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Find contours (in inverted thresh)
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = imutils.grab_contours(cnts)

# Find the contour with the maximum area.
c = max(cnts, key=cv2.contourArea)

# Get bounding rectangle
x, y, w, h = cv2.boundingRect(c)

# Crop the bounding rectangle out of thresh
thresh_card = thresh[y:y+h, x:x+w].copy()

# OCR
result = pytesseract.image_to_string(thresh_card)
print(f"OCR Results:\n {result}")


# Show images for debugging
cv2.imshow('s', s)
cv2.imshow('thresh', thresh)
cv2.imshow('thresh_card', thresh_card)
cv2.waitKey(0)
cv2.destroyAllWindows()

OCR 結果:

 Visa Classic

| By)

4000 1234 Sb18 9010

CARDHOLDER MARE
VISA

還是不完美...


s:
在此處輸入圖片說明

閾值:
在此處輸入圖片說明

閾值卡:
在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM