TShopping

 找回密碼
 註冊
搜索
查看: 1996|回復: 0

[教學] opencv 信用卡數字識別(opencv4.4測試OK)

[複製鏈接]
發表於 2020-12-24 22:59:48 | 顯示全部樓層 |閱讀模式
 
Push to Facebook
信用卡數字識別-流程預覽(可執行代碼請看頁尾)

opencv 信用卡 數字識別

opencv 信用卡 數字識別

一、基礎配置
  1. # 匯入工具包
  2. from imutils import contours
  3. import numpy as np
  4. import argparse
  5. import cv2
  6. import myutils

  7. # 設定引數
  8. ap = argparse.ArgumentParser()
  9. ap.add_argument("-i","--image",default='./images/credit_card_01.png',help="path to input image")
  10. ap.add_argument("-t","--template",default='./ocr_a_reference.png',help="path to template OCR image")
  11. args = vars(ap.parse_args())
  12. # 指定信用卡型別
  13. FIRST_NUMBER = {"3": "American Express","4": "Visa","5": "MasterCard","6": "Discover Card"}
  14. # 繪圖展示
  15. def cv_show(name,img):
  16.         cv2.imshow(name, img)
  17.         cv2.waitKey(0)
  18.         cv2.destroyAllWindows()
複製代碼





二、模板處理

模板處理流程: 輪廓檢測, 外接矩形, 摳出模板, 讓模板對應每個數值
字典digits = {} # 存模板的單個數字

  1. # 讀取一個模板影象
  2. img = cv2.imread(args["template"])
  3. cv_show('template',img)
  4. # 灰度圖
  5. ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  6. cv_show('template_gray',ref)
  7. # 二值影象
  8. ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
  9. cv_show('template_bi',ref)

  10. # 1.計算輪廓
  11. # cv2.findContours()函式接受的引數為二值圖,即黑白的(不是灰度圖),cv2.RETR_EXTERNAL只檢測外輪廓,cv2.CHAIN_APPROX_SIMPLE只保留終點座標
  12. # 返回的list中每個元素都是影象中的一個輪廓
  13. refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)        # cv版本大於3.8的,只有兩個返回值

  14. cv2.drawContours(img,refCnts,-1,(0,0,255),3)         # 輪廓在二值圖上得到, 畫要畫在原圖上
  15. cv_show('template_Contours',img)
  16. print (np.array(refCnts).shape)
  17. refCnts = myutils.sort_contours(refCnts, method="left-to-right")[0] #排序,從左到右,從上到下
  18. digits = {}        # 存模板的單個數字

  19. # 2.遍歷每一個輪廓,外接矩形
  20. for (i, c) in enumerate(refCnts):        # c是每個輪廓的終點座標
  21.         # 計算外接矩形並且resize成合適大小
  22.         (x, y, w, h) = cv2.boundingRect(c)
  23.         # 3.摳出模板
  24.         roi = ref[y:y + h, x:x + w]                # 每個roi對應一個數字
  25.         roi = cv2.resize(roi, (57, 88))        # 太小,調大點

  26.         # 4.每一個數字對應每一個模板
  27.         digits[i] = roi
複製代碼

opencv 信用卡 數字識別

opencv 信用卡 數字識別

注:在自己動手實踐過程中,發現有以下幾個點需要注意(順一遍沒有大問題的同學, 可先跳過此處)

  • Line 8:因findCoutours 檢測黑底白字的物體,所以要選擇反轉的二值化THRESH_BINARY_INV
  • Line 14:我們需要外輪廓,畫外接矩形,所以用cv2.RETR_EXTERNAL
  • Line 23:enumerate() 函式用於將一個可遍歷的資料物件(如列表、元組或字串)組合為一個索引序列

seq = [‘one’, ‘two’, ‘three’]
for i, element in enumerate(seq):
… print i, element

0 one
1 two
2 three





  • Line 27:側重於摳出單個數值的模板,而不是畫個rectangle
  • Line 20,31:digits設定為字典,第i個健對應的第i個模板數值roi
  • Line 19:對輪廓進行排序,並且返回兩個值,只需要輪廓[0]
    refCnts = myutils.sort_contours(refCnts, method=“left-to-right”)[0]

排序前

opencv 信用卡 數字識別

opencv 信用卡 數字識別

排序後

opencv 信用卡 數字識別

opencv 信用卡 數字識別

也可以不排序,在後面數值與模板數值匹配時需要做相應改動,感興趣的同學自行研究

對輪廓進行排序的程式碼如下:

  1. def sort_contours(cnts, method="left-to-right"):
  2.     reverse = False
  3.     i = 0

  4.     if method == "right-to-left" or method == "bottom-to-top":
  5.         reverse = True

  6.     if method == "top-to-bottom" or method == "bottom-to-top":
  7.         i = 1

  8.     # 計算外接矩形 boundingBoxes是一個元組
  9.     boundingBoxes = [cv2.boundingRect(c) for c in cnts] #用一個最小的矩形,把找到的形狀包起來x,y,h,w
  10.     # sorted排序
  11.     (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
  12.                                         key=lambda b: b[1][i], reverse=reverse))

  13.     return cnts, boundingBoxes  # 輪廓和boundingBoxess
複製代碼



三、輸入影象處理

opencv 信用卡 數字識別

opencv 信用卡 數字識別

  1. # 1.初始化卷積核,根據實際任務指定大小,不一定非要3x3
  2. rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
  3. sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

  4. # 2.讀取輸入影象,預處理
  5. image = cv2.imread(args["image"])
  6. cv_show('Input_img',image)
  7. image = myutils.resize(image, width=300)
  8. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  9. cv_show('Input_gray',gray)

  10. # 3.禮帽操作,突出更明亮的區域
  11. # 形態學操作,禮帽+閉操作可以突出明亮區域,但並不是非得禮帽+閉操作
  12. tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)
  13. cv_show('Input_tophat',tophat)
  14. # 4.x方向的Sobel運算元,實驗表明,加y的效果的並不好
  15. gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0,ksize=-1) #ksize=-1相當於用3*3的

  16. # x方向取絕對值 -> 歸一化
  17. gradX = np.absolute(gradX)        # absolute: 計算絕對值
  18. (minVal, maxVal) = (np.min(gradX), np.max(gradX))
  19. gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
  20. gradX = gradX.astype("uint8")

  21. print (np.array(gradX).shape)
  22. cv_show('Input_Sobel_gradX',gradX)

  23. # 5.通過閉操作(先膨脹,再腐蝕)將數字連在一起.  將本是4個數字的4個框膨脹成1個框,就腐蝕不掉了
  24. gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
  25. cv_show('Input_CLOSE_gradX',gradX)

  26. # 6.THRESH_OTSU會自動尋找合適的閾值,適合雙峰,需把閾值引數設定為0
  27. thresh = cv2.threshold(gradX, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  28. cv_show('Input_thresh',thresh)

  29. # 7.再來一個閉操作
  30. thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) # 填補空洞
  31. cv_show('Input_thresh_CLOSE',thresh)

  32. # 8.計算輪廓
  33. threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
  34.         cv2.CHAIN_APPROX_SIMPLE)

  35. cnts = threshCnts
  36. cur_img = image.copy()
  37. cv2.drawContours(cur_img,cnts,-1,(0,0,255),3)
  38. cv_show('Input_Contours',cur_img)
複製代碼

opencv 信用卡 數字識別

opencv 信用卡 數字識別



opencv 信用卡 數字識別

opencv 信用卡 數字識別

注:

  • Line 20-23:絕對值+歸一化
    歸一化 x’ = (x-min)/(max-min)
  • Line 36:第二個閉操作換個9x9的核
    onekernel = np.ones((9,9), np.uint8)
    thresh = cv2.morphologyEx(thresh,cv2.MORPH_CLOSE,onekernel)

opencv 信用卡 數字識別

opencv 信用卡 數字識別

四、遍歷輪廓

  1. # 1.遍歷輪廓
  2. locs = []        # 存符合條件的輪廓
  3. for i,c in enumerate(threshCnts):
  4.         # 計算矩形
  5.         x,y,w,h = cv2.boundingRect(c)

  6.         ar = w / float(h)
  7.         # 選擇合適的區域,根據實際任務來,這裡的基本都是四個數字一組
  8.         if ar > 2.5 and ar < 4.0:
  9.                 if (w > 40 and w < 55) and (h > 10 and h < 20):
  10.                         #符合的留下來
  11.                         locs.append((x, y, w, h))        

  12. # 將符合的輪廓從左到右排序
  13. locs = sorted(locs,key=lambda x:x[0])
複製代碼

注:

  • Line 6-11:根據w和h的比例,選出包括4個數字的區域,視實際情況判定
  • Line 14:
    key=lambda 元素: 元素[欄位索引]
    C = (sorted(C, key=lambda x: x[0]))
    x:x[]字母可以隨意修改,排序方式按照中括號[]裡面的維度,[0]按照第一維,[1]按照第二維。

五、遍歷數字

  1. # 2.遍歷每一個輪廓中的數字
  2. output = []        # 存正確的數字
  3. for (i,(gx,gy,gw,gh)) in enumerate(locs):        # 遍歷每一組大輪廓(包含4個數字)
  4.         # initialize the list of group digits
  5.         groupOutput = []

  6.         # 根據座標提取每一個組(4個值)
  7.         group = gray[gy-5:gy+gh+5, gx-5:gx+gw+5]        # 往外擴一點
  8.         cv_show('group_'+str(i),group)
  9.         # 2.1 預處理
  10.         group = cv2.threshold(group,0,255,cv2.THRESH_BINARY|cv2.THRESH_OTSU)[1]        # 二值化的group
  11.         # cv_show('group_'+str(i),group)
  12.                 # 計算每一組的輪廓 這樣就分成4個小輪廓了
  13.         digitCnts = cv2.findContours(group.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[0]
  14.                 # 排序
  15.         digitCnts = myutils.sort_contours(digitCnts,method="left-to-right")[0]

  16.         # 2.2 計算並匹配每一組中的每一個數值
  17.         for c in digitCnts:        # c表示每個小輪廓的終點座標
  18.                 z = 0
  19.                 # 找到當前數值的輪廓,resize成合適的的大小
  20.                 (x,y,w,h) = cv2.boundingRect(c)        # 外接矩形
  21.                 roi = group[y:y+h,x:x+w]                # 在原圖中取出小輪廓覆蓋區域,即數字
  22.                 roi = cv2.resize(roi, (57, 88))
  23.                 # cv_show("roi_"+str(z),roi)
  24.                
  25.                 # 計算匹配得分: 0得分多少,1得分多少...
  26.                 scores = []        # 單次迴圈中,scores存的是一個數值 匹配 10個模板數值的最大得分

  27.                 # 在模板中計算每一個得分
  28.                 # digits的digit正好是數值0,1,...,9;digitROI是每個數值的特徵表示
  29.                 for (digit,digitROI) in digits.items():
  30.                         # 進行模板匹配, res是結果矩陣
  31.                         res = cv2.matchTemplate(roi,digitROI,cv2.TM_CCOEFF)        # 此時roi是X digitROI是0 依次是1,2.. 匹配10次,看模板最高得分多少
  32.                         Max_score = cv2.minMaxLoc(res)[1]        # 返回4個,取第二個最大值Maxscore
  33.                         scores.append(Max_score)        # 10個最大值
  34.                 print("scores:",scores)
  35.                 # 得到最合適的數字
  36.                 groupOutput.append(str(np.argmax(scores)))        # 返回的是輸入列表中最大值的位置
  37.                 z = z+1
  38.         # 2.3 畫出來
  39.         cv2.rectangle(image,(gx-5,gy-5),(gx+gw+5,gy+gh+5),(0,0,255),1)        # 左上角,右下角
  40.         # 2.4 putText引數:圖片,新增的文字,左上角座標,字型,字型大小,顏色,字型粗細
  41.         cv2.putText(image,"".join(groupOutput),(gx,gy-15),
  42.                                 cv2.FONT_HERSHEY_SIMPLEX,0.65,(0,0,255),2)

  43.         # 2.5 得到結果
  44.         output.extend(groupOutput)
  45.         print("groupOutput:",groupOutput)
複製代碼

opencv 信用卡 數字識別

opencv 信用卡 數字識別

注:

  • 二的digits 是 模板中的單個數值(即五中的digitROI)
  • 五的digitCnts -> group -> roi 是 輸入圖中的單個數值
  • 輸入圖中的單個數值 和 模板中的單個數值 需進行相同的resize,否則無法進行匹配
    roi = cv2.resize(roi, (57, 88))
  • Line 11:對group的二值化預處理時(即 將一組輪廓group(4數字) 分為 4個小輪廓digitCnts前),必須加上cv2.THRESH_OTSU,否則檢測不出4個小輪廓
  • Line 44:groupOutput中存的是每一組(4個)數值 如4000,因此在putText時,數值中間就不用空格或其他內容了,雙引號""中間沒有任何東西。
    putText引數:圖片,新增的文字,左上角座標,字型,字型大小,顏色,字型粗細
    putText的第3個引數是左上角的座標,因此在列印下一組groupOutput,它會重新以這組的(gx,gy-15)為新左上角座標

六、識別結果

  1. # 列印結果
  2. print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
  3. print("Credit Card #: {}".format("".join(output)))
  4. cv2.imshow("Output_image", image)
  5. cv2.waitKey(0)
複製代碼
輸出:
  1. (10,)
  2. (189, 300)
  3. groupOutput: ['4', '0', '0', '0']
  4. groupOutput: ['1', '2', '3', '4']
  5. groupOutput: ['5', '6', '7', '8']
  6. groupOutput: ['9', '0', '1', '0']
  7. Credit Card Type: Visa
  8. Credit Card #: 4000123456789010
複製代碼



opencv 信用卡 數字識別

opencv 信用卡 數字識別

附:測試另外幾張信用卡數字識別的效果

opencv 信用卡 數字識別

opencv 信用卡 數字識別


  1. # Import toolkit
  2. from imutils import contours
  3. import imutils
  4. import numpy as np
  5. import argparse
  6. import cv2
  7. import myutils

  8. # Specify credit card type
  9. FIRST_NUMBER = {
  10.     "3": "American Express",
  11.     "4": "Visa",
  12.     "5": "MasterCard",
  13.     "6": "Discover Card"
  14. }
  15. # Drawing display
  16. def cv_show(name,img):
  17.     cv2.imshow(name, img)
  18.     cv2.waitKey(0)
  19.     cv2.destroyAllWindows()
  20. # Read a template image
  21. img = cv2.imread('temp.png')
  22. cv_show('img',img)
  23. # Grayscale image
  24. ref = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  25. cv_show('ref',ref)
  26. # Binary image
  27. ref = cv2.threshold(ref, 10, 255, cv2.THRESH_BINARY_INV)[1]
  28. cv_show('ref',ref)

  29. # Calculate contour The parameter accepted by the #cv2.findContours() function is a binary image, that is, black and white (not grayscale), cv2.RETR_EXTERNAL only detects the outer contour, and cv2.CHAIN_APPROX_SIMPLE only retains the end point coordinates
  30. # Each element in the returned list is an outline in the image

  31. refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

  32. cv2.drawContours(img,refCnts,-1,(0,0,255),3)
  33. cv_show('img',img)
  34. print (np.array(refCnts).shape)
  35. refCnts = sorted(refCnts, key=lambda refCnts: cv2.boundingRect(refCnts)[0])
  36. digits = {}

  37. for (i, c) in enumerate(refCnts):
  38.     # Calculate the circumscribed rectangle and resize it to a suitable size
  39.     (x, y, w, h) = cv2.boundingRect(c)
  40.     roi = ref[y:y + h, x:x + w]
  41.     roi = cv2.resize(roi, (57, 88))

  42.     # Each number corresponds to each template
  43.     digits[i] = roi

  44. # Initialize the convolution kernel
  45. rectKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (9, 3))
  46. sqKernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))

  47. #Read input image, preprocess
  48. image = cv2.imread('xin.png')
  49. cv_show('image',image)
  50. #image = imutils.resize(image, height=900,width=900)
  51. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  52. cv_show('gray',gray)

  53. #Top hat operation to highlight brighter areas
  54. tophat = cv2.morphologyEx(gray, cv2.MORPH_TOPHAT, rectKernel)
  55. cv_show('tophat',tophat)

  56. gradX = cv2.Sobel(tophat, ddepth=cv2.CV_32F, dx=1, dy=0, ksize=-1)


  57. gradX = np.absolute(gradX)
  58. (minVal, maxVal) = (np.min(gradX), np.max(gradX))
  59. gradX = (255 * ((gradX - minVal) / (maxVal - minVal)))
  60. gradX = gradX.astype("uint8")

  61. print (np.array(gradX).shape)
  62. cv_show('gradX',gradX)

  63. #Connect the numbers together by closing operation (expansion first, then corrosion)
  64. gradX = cv2.morphologyEx(gradX, cv2.MORPH_CLOSE, rectKernel)
  65. cv_show('gradX',gradX)
  66. #THRESH_OTSU will automatically find a suitable threshold, suitable for double peaks, you need to set the threshold parameter to 0
  67. thresh = cv2.threshold(gradX, 0, 255,cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  68. cv_show('thresh',thresh)

  69. # Close operation

  70. thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, sqKernel) #Another closed operation
  71. cv_show('thresh',thresh)

  72. # Calculate contour

  73. threshCnts, hierarchy = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

  74. cnts = threshCnts
  75. cur_img = image.copy()
  76. cv2.drawContours(cur_img,cnts,-1,(0,0,255),3)
  77. cv_show('img',cur_img)
  78. locs = []

  79. # Traverse the outline
  80. for (i, c) in enumerate(cnts):
  81.     # Calculate rectangle
  82.     (x, y, w, h) = cv2.boundingRect(c)
  83.     ar = w / float(h)

  84.     # Select the appropriate area, according to the actual task, basically here are a group of four numbers
  85.     if ar > 2.5 and ar < 4.0:
  86.          if (w > 40 and w < 55) and (h > 10 and h < 20):
  87.             #Consistent stay
  88.             locs.append((x, y, w, h))

  89. # Sort matching contours from left to right
  90. locs = sorted(locs, key=lambda x:x[0])
  91. output = []

  92. # Iterate over the numbers in each outline
  93. for (i, (gX, gY, gW, gH)) in enumerate(locs):
  94.     # initialize the list of group digits
  95.     groupOutput = []

  96.     # Extract each group according to coordinates
  97.     group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
  98.     cv_show('group',group)
  99.     # Preprocessing
  100.     group = cv2.threshold(group, 0, 255,
  101.         cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
  102.     cv_show('group',group)
  103.     # Calculate the outline of each group
  104.     digitCnts,hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
  105.     digitCnts = contours.sort_contours(digitCnts,
  106.         method="left-to-right")[0]

  107.     # Calculate each value in each group
  108.     for c in digitCnts:
  109.         # Find the outline of the current value and resize it to a suitable size
  110.         (x, y, w, h) = cv2.boundingRect(c)
  111.         roi = group[y:y + h, x:x + w]
  112.         roi = cv2.resize(roi, (57, 88))
  113.         cv_show('roi',roi)

  114.         # Calculate match score
  115.         scores = []

  116.         # Calculate each score in the template
  117.         for (digit, digitROI) in digits.items():
  118.             # Template matching
  119.             result = cv2.matchTemplate(roi, digitROI,cv2.TM_CCOEFF)
  120.             (_, score, _, _) = cv2.minMaxLoc(result)
  121.             scores.append(score)

  122.         # Get the most suitable number
  123.         groupOutput.append(str(np.argmax(scores)))

  124.     # Draw it
  125.     cv2.rectangle(image, (gX - 5, gY - 5),(gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
  126.     cv2.putText(image, "".join(groupOutput), (gX, gY - 15),cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)

  127.     # got the answer
  128.     output.extend(groupOutput)

  129. # Print result
  130. #print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
  131. print("Credit Card #: {}".format("".join(output)))
  132. cv2.imshow("Image", image)
  133. cv2.waitKey(0)
複製代碼


文章出處

網頁設計,網站架設 ,網路行銷,網頁優化,SEO - NetYea 網頁設計

 

臉書網友討論
*滑块验证:
您需要登錄後才可以回帖 登錄 | 註冊 |

本版積分規則



Archiver|手機版|小黑屋|免責聲明|TShopping

GMT+8, 2024-3-29 01:02 , Processed in 0.063167 second(s), 26 queries .

本論壇言論純屬發表者個人意見,與 TShopping綜合論壇 立場無關 如有意見侵犯了您的權益 請寫信聯絡我們。

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回復 返回頂部 返回列表