本項目利用python以及opencv實現信用卡的數字識別
前期準備
模板圖像處理
讀取模板圖像 cv2.imread(img) 灰度化處理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 二值化 cv2.threshold() 輪廓 - 輪廓信用卡圖像處理
讀取信用卡圖像 cv2.imread(img) 灰度化處理 cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) 禮帽處理 cv2.morphologyEx(gray,cv2.MORPH_TOPHAT,rectKernel) Sobel邊緣檢測 cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1) 閉操作 cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel) 計算輪廓 cv2.findContours 模板檢測 cv2.matchTemplate(roi, digitROI,cv2.TM_CCOEFF)原始數據展示
結果展示
1 前期準備
# 導入工具包# opencv讀取圖片的格式為b g r# matplotlib圖片的格式為 r g bimport numpy as npimport cv2from imutils import contoursimport matplotlib.pyplot as plt%matplotlib inline
# 信用卡的位置predict_card = "images/credit_card_01.png"# 模板的位置template = "images/ocr_a_reference.png"
# 指定信用卡類型FIRST_NUMBER = { "3": "American Express", "4": "Visa", "5": "MasterCard", "6": "Discover Card"}
# 定義一些功能函數# 對框進行排序def sort_contours(cnts, method="left-to-right"): reverse = False i = 0 if method == "right-to-left" or method == "bottom-to-top": reverse = True if method == "top-to-bottom" or method == "bottom-to-top": i = 1 boundingBoxes = [cv2.boundingRect(c) for c in cnts] #用一個最小的矩形,把找到的形狀包起來x,y,h,w (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b: b[1][i], reverse=reverse)) return cnts, boundingBoxes# 調整圖片尺寸大小def resize(image, width=None, height=None, inter=cv2.INTER_AREA): dim = None (h, w) = image.shape[:2] if width is None and height is None: return image if width is None: r = height / float(h) dim = (int(w * r), height) else: r = width / float(w) dim = (width, int(h * r)) resized = cv2.resize(image, dim, interpolation=inter) return resized# 定義cv2展示函數def cv_show(name,img): cv2.imshow(name,img) cv2.waitKey(0) cv2.destroyAllWindows()
2 對模板圖像進行預處理操作
讀取模板圖像
# 讀取模板圖像img = cv2.imread(template)cv_show("img",img)plt.imshow(img)
新聞熱點
疑難解答