本实例深入剖析了信用卡数字识别技术,通过图像处理方法提高数字识别精度,为金融行业提供高效、准确的数据处理方案。
首先处理模板图像:
1. 读取并转换为灰度图:
```python
tempalte_img = cv.imread(E:/opencv/picture/ocr_a_reference.png)
tempalte_gray = cv.cvtColor(tempalte_img, cv.COLOR_BGR2GRAY)
```
2. 应用二值化处理:
```python
tempalte_thres = cv.threshold(tempalte_gray, 0, 255, cv.THRESH_OTSU | cv.THRESH_BINARY_INV)[1]
```
3. 寻找轮廓并绘制在模板图像上:
```python
temp_a, tempalte_contours, temp_b = cv.findContours(tempalte_thres.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(tempalte_img, tempalte_contours, -1, (0, 255, 0), 2)
```
4. 排序轮廓并提取数字区域:
```python
tempalte_contours = contours.sort_contours(tempalte_contours, method=left-to-right)[0]
digits = {}
for (i, c) in enumerate(tempalte_contours):
x, y, w, h = cv.boundingRect(c)
tempalte_roi = tempalte_thres[y:y + h, x:x + w]
tempalte_roi = cv.resize(tempalte_roi, (57, 88))
digits[i] = tempalte_roi
```
接下来,处理银行卡图像:
1. 调整大小和转换为灰度图:
```python
image = cv.imread(E:/opencv/picture/credit_card_02.png)
image = myutils.resize(image, width=300)
image_gray = cv.cvtColor(image,cv.COLOR_BGR2GRAY)
```
2. 应用形态学操作以增强图像特征:
```python
rectkernel = cv.getStructuringElement(cv.MORPH_RECT,(9,3))
squrkernel = cv.getStructuringElement(cv.MORPH_RECT,(5,5))
image_tophat= cv.morphologyEx(image_gray,cv.MORPH_TOPHAT,rectkernel)
image_close = cv.morphologyEx(image_tophat,cv.MORPH_CLOSE,rectkernel)
cv.imshow(image_tophat,image_tophat)
```
3. 二值化处理:
```python
image_thres= cv.threshold(image_close,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)[1]
image_contours = cv.findContours(image_thres.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)[1]
locs = []
for (n, con) in enumerate(image_contours):
gx, gy, gw, gh = cv.boundingRect(con)
ar = gw / float(gh)
if ar > 2.5 and ar < 4.0:
if (gw > 40 and gw < 55) and (gh > 10 and gh < 20):
locs.append((gx, gy, gw, gh))
```
4. 排序找到的轮廓:
```python
locs = sorted(locs, key=lambda x:x[0])
output = []
for (i,(x,y,w,h)) in enumerate(locs):
groupOutput = []
group = image_gray[y-5:y+h+5,x-5:x+w+5]
group = cv.threshold(group,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)[1]
digcnts = cv.findContours(group.copy(),cv.RETR_EXTERNAL,cv.CHAIN_APPROX_SIMPLE)[1]
digcnts = contours.sort_contours(digcnts,method=left-to-right)[0]
for c in digcnts:
gx, gy, gw, gh = cv.boundingRect(c)
roi = group[gy:gy+gh,gx:gx+gw]
roi = cv.resize(roi,(57,88))
scores = []
for (digit,digitROI) in digits.items():
result = cv.matchTemplate(roi, digitROI, cv.TM_CCOEFF_NORMED)
_, score, _, _ = cv.minMaxLoc(result)
scores.append(score)
groupOutput.append(str(np.argmax(scores)))
output.extend(groupOutput)
```
5. 显示结果:
```python
for (i,(x,y,w,h)) in enumerate(locs):
cv.rectangle(image, (x - 5, y - 5), (x + w + 5, y + h + 5), (