OpenCV学习(一)银行卡号识别

  • B站教学链接: 

银行卡号识别(OpenCV-Python)

代码:Card_Number_Recognition

1.方法

使用模板匹配的方法来识别银行卡号数字。具体来说,先通过图像预处理将图像中的银行卡号分割出来,再与提供的模板进行对比,从而完成银行卡号的识别。

2.代码

##############################
###   Bank card number identification
##############################

import cv2
import numpy as np

card_GRAY=cv2.imread('bank_card41.jpg',0)
card_GRAY4=cv2.resize(card_GRAY,(4*card_GRAY.shape[1],4*card_GRAY.shape[0]))
#cv2.imshow('card_GRAY4',card_GRAY4)

adaptiveThresh = cv2.adaptiveThreshold(card_GRAY4, 255, cv2.ADAPTIVE_THRESH_MEAN_C, 
                                       cv2.THRESH_BINARY_INV, 13, 3)
#cv2.imshow('adaptiveThresh',adaptiveThresh)

contours, hierarchy = cv2.findContours(adaptiveThresh,cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
    if cv2.contourArea(contours[i])<160:
        adaptiveThresh = cv2.drawContours(adaptiveThresh, contours, i, (0,0,0), -1)
#cv2.imshow('adaptiveThresh2',adaptiveThresh)

kernel = np.ones((15,15),dtype=np.uint8)
blackhat = cv2.morphologyEx(adaptiveThresh, cv2.MORPH_BLACKHAT, kernel)
#cv2.imshow('blackhat',blackhat)

kernel = np.ones((3,3),dtype=np.uint8)
opening = cv2.morphologyEx(blackhat, cv2.MORPH_OPEN, kernel)
#cv2.imshow('opening',opening)

contours, hierarchy = cv2.findContours(opening,cv2.RETR_TREE,
                                       cv2.CHAIN_APPROX_SIMPLE)
for i in range(len(contours)):
    x,y,w,h = cv2.boundingRect(contours[i])
    aspect_ratio = float(w)/h
    Area = w * h
    if Area<1800 or Area>6000:
        opening = cv2.drawContours(opening, contours, i, (0,0,0), -1)
    else:
        if aspect_ratio>0.7 or aspect_ratio<0.5:
            opening = cv2.drawContours(opening, contours, i, (0,0,0), -1)
cv2.imshow('opening2',opening)

kernel = np.ones((5,5),np.uint8)
dilation = cv2.dilate(opening,kernel,iterations = 1)
cv2.imshow('dilation',dilation)

numTemplate=cv2.imread('bankCardNumTemplate.jpg')
numTemplate_GRAY=cv2.cvtColor(numTemplate,cv2.COLOR_BGR2GRAY)
ret,numTemplate_GRAY = cv2.threshold(numTemplate_GRAY,200,255,cv2.THRESH_BINARY)
cv2.imshow('numTemplate_GRAY',numTemplate_GRAY)

def sequence_contours(image, width, height):
    contours, hierarchy = cv2.findContours(image,cv2.RETR_EXTERNAL,
                                           cv2.CHAIN_APPROX_SIMPLE)
    n = len(contours)
    RectBoxes0 = np.ones((n,4),dtype=int)
    for i in range(n):
        RectBoxes0[i] = cv2.boundingRect(contours[i])
    
    RectBoxes = np.ones((n,4),dtype=int)
    for i in range(n):
        sequence = 0
        for j in range(n):
            if RectBoxes0[i][0]>RectBoxes0[j][0]:
                sequence = sequence + 1
        RectBoxes[sequence] = RectBoxes0[i]
        
    ImgBoxe
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值