基于opencv的银行卡识别
时间: 2023-12-03 09:40:05 浏览: 232
基于OpenCV的银行卡识别可以通过以下步骤实现:
1.读取图像并将其转换为灰度图像和二进制图像。
```python
import cv2
import matplotlib.pyplot as plt
def read(img, thresh=127, inv=False):
origin = cv2.imread(img)
gray = cv2.imread(img, 0)
binary = cv2.threshold(gray, thresh, 255, cv2.THRESH_BINARY_INV if inv else cv2.THRESH_BINARY)[1]
return origin, gray, binary
```
2.将图像中的银行卡区域提取出来。
```python
def extract_card(img):
_, contours, _ = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv2.contourArea, reverse=True)
for contour in contours:
perimeter = cv2.arcLength(contour, True)
approx = cv2.approxPolyDP(contour, 0.02 * perimeter, True)
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(contour)
return x, y, w, h
```
3.将银行卡区域与模板进行匹配,找到银行卡号码的位置。
```python
def match_template(img, template):
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(res)
return max_val, max_loc
```
4.将银行卡号码数字割出来,并与模板比较,选出相似度最高的答案。
```python
def extract_number(img, x, y, w, h):
number_img = img[y:y+h, x:x+w]
number_img = cv2.resize(number_img, (w*5, h*5))
_, number_img = cv2.threshold(number_img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
number_img = cv2.resize(number_img, (w, h))
return number_img
def match_number(number_img, templates):
max_val = 0
max_index = 0
for i, template in enumerate(templates):
val, _ = match_template(number_img, template)
if val > max_val:
max_val = val
max_index = i
return max_index
```
阅读全文