# 简介:
银行卡识别、练手项目、图像识别、OCR
# 1. 在 ocr_template_match.py 中计算模板数字 0~9 的轮廓,并保存备用
# 计算轮廓
# cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),
# cv2.RETR_EXTERNAL只检测外轮廓,cv2.CHAIN_APPROX_SIMPLE只保留终点坐标
# 返回的list中每个元素都是图像中的一个轮廓
# ref_, refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
refCnts, hierarchy = cv2.findContours(ref.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 特判 refCnts > 0, 防止
if len(refCnts) > 0:
# 绘制轮廓
cv2.drawContours(img, refCnts, -1, (0, 0, 255), 3)
cv_show('img', img)
else:
print("No contours found.")
# print(len(refCnts))
# 输出 1,并不为 null
# cv2.drawContours(img,refCnts,-1,(0,0,255),3)
# cv_show('img',img)
# 打印维度值 "shape" 通常是指多维数组或矩阵的维度和大小
# 一维数组的 "shape" 是 (n,),其中 n 表示数组中元素的数量。
# (10, ) 表示
shapes = [np.array(cnt).shape for cnt in refCnts]
print(shapes)
print(np.array(shapes).shape)
# print(len(refCnts))
# ValueError: setting an array element with a sequence.
# The requested array has an inhomogeneous shape after 1 dimensions.
# The detected shape was (10,) + inhomogeneous part.
# print(np.array(refCnts).shape)
# 排序,从左到右,从上到下 (为了将 0 ~ 9 进行区分,返回排序完的轮廓)
refCnts = myutils.sort_contours(refCnts, method="left-to-right")[0]
# 2. 在 ocr_template_match.py 中计算银行卡号轮廓后,做模板匹配
# 遍历每一个轮廓中的数字
for (i, (gX, gY, gW, gH)) in enumerate(locs):
# initialize the list of group digits
groupOutput = []
# 输出每个轮廓的 x, y, w, h
# print(gX)
# print(gY)
# print(gW)
# print(gH)
# 将一组数据的轮廓扩大 5 个单位
# 根据坐标提取每一个组
group = gray[gY - 5:gY + gH + 5, gX - 5:gX + gW + 5]
cv_show('group',group)
# 预处理
group = cv2.threshold(group, 0, 255,
cv2.THRESH_BINARY | cv2.THRESH_OTSU)[1]
cv_show('group',group)
# 计算每一组的轮廓
# group_, digitCnts, hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
# cv2.CHAIN_APPROX_SIMPLE)
digitCnts, hierarchy = cv2.findContours(group.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
digitCnts = contours.sort_contours(digitCnts,
method="left-to-right")[0]
# 计算每一组中的每一个数值
for c in digitCnts:
# 找到当前数值的轮廓,resize成合适的的大小
# x, y, w, h 是单个数字的坐标和长宽
(x, y, w, h) = cv2.boundingRect(c)
roi = group[y:y + h, x:x + w]
roi = cv2.resize(roi, (57, 88))
cv_show('roi',roi)
# 计算匹配得分
scores = []
# 在模板中计算每一个得分
for (digit, digitROI) in digits.items():
# 模板匹配
result = cv2.matchTemplate(roi, digitROI, cv2.TM_CCOEFF)
(_, score, _, _) = cv2.minMaxLoc(result)
scores.append(score)
# 得到最合适的数字
groupOutput.append(str(np.argmax(scores)))
# 画出来
cv2.rectangle(image, (gX - 5, gY - 5),
(gX + gW + 5, gY + gH + 5), (0, 0, 255), 1)
cv2.putText(image, "".join(groupOutput), (gX, gY - 15),
cv2.FONT_HERSHEY_SIMPLEX, 0.65, (0, 0, 255), 2)
# 得到结果
output.extend(groupOutput)
# 打印结果
print("Credit Card Type: {}".format(FIRST_NUMBER[output[0]]))
print("Credit Card #: {}".format("".join(output)))
cv2.imshow("Image", image)
cv2.waitKey(0)
# 3. 效果展示
