写在前面
本篇文章是opencv学习的第六篇文章,前面主要讲解了对图像的一些基本操作,这篇文章我们就开始大展身手,将前面所学的基础操作活学活用。既能复习基础操作,又能学到一些新的知识。作为初学者,我尽己所能,但仍会存在疏漏的地方,希望各位看官不吝指正🥰
写在中间
( 1 )简单介绍
( 2 )操作步骤
对模板
- 读取数字模板图像
cv2.imread()

-
数字模板转换为灰度图
cv2.cvtcolor() -
灰度图转换为二值图
cv2.threshold(),并实现对图像的黑白反转

- 对二值图轮廓检测
cv2.findcontours(),只检测外轮廓且保存对角线上的点;

- 将轮廓从左到右依次排序
contours.sort_contours(),之后遍历每一个轮廓
对目标图像
- 读取信用卡图像
cv2.imread()

- 信用卡图重构大小,并转换为灰度图

- 礼帽操作
cv2.morphologyex()。突出明亮的部分,过滤较暗的部分

- sobel算子边缘检测
cv2.sobel()

- 闭操作(先膨胀再腐蚀)+二值化+闭操作

- 计算并画出轮廓
cv2.findcontours()、cv2.drawcontours()

- 下面的操作还有很多:遍历轮廓,筛选出数字轮廓,将数字轮廓进行排序,对四组轮廓每组都灰度处理,提取数字轮廓,将数字轮廓与模板数字轮廓比对,得出数字结果,最后绘制出来,大致效果如下:

( 3 )代码展示
# 导入工具包
from imutils import contours
import numpy as np
import argparse
import cv2
import myutils
# 设置参数
# ap = argparse.argumentparser()
# ap.add_argument("-i", "--image", required=true,
# help="path to input image")
# ap.add_argument("-t", "--template", required=true,
# help="path to template ocr-a image")
# args = vars(ap.parse_args())
# 指定信用卡类型
first_number = {
"3": "american express",
"4": "visa",
"5": "mastercard",
"6": "discover card"
}
# 绘图展示
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitkey(0)
cv2.destroyallwindows()
# 轮廓排序
def sort_contours(cnts, method="left-to-right"):
reverse = false
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = true
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingboxes = [cv2.boundingrect(c) for c in cnts] # 用一个最小的矩形,把找到的形状包起来x,y,h,w
(cnts, boundingboxes) = zip(*sorted(zip(cnts, boundingboxes), key=lambda b: b[1][i], reverse=reverse))
return cnts, boundingboxes
def resize(image, width=none, height=none, inter=cv2.inter_area):
dim = none
(h, w) = image.shape[:2]
if width is none and height is none:
return image
if width is none:
r = height / float(h)
dim = (int(w * r), height)
else:
r = width / float(w)
dim = (width, int(h * r))
resized = cv2.resize(image, dim, interpolation=inter)
return resized
# 读取一个模板图像
img = cv2.imread("d:\python\program\pythonproject\photos\p_5_0.png")
cv_show('img', img)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_5.jpg", img)
# 灰度图,颜色通道bgr to gray
ref = cv2.cvtcolor(img, cv2.color_bgr2gray)
cv_show('ref', ref)
# 二值图像(因为模板的边缘都是白色的)
ref = cv2.threshold(ref, 10, 255, cv2.thresh_binary_inv)[1]
cv_show('ref', ref)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_6.jpg", ref)
# 计算轮廓
# cv2.findcontours()函数接受的参数为二值图,即黑白的(不是灰度图),
# cv2.retr_external只检测外轮廓(需要得到他的外接矩形),
# cv2.chain_approx_simple只保留终点坐标
# 返回的list中每个元素都是图像中的一个轮廓
refcnts, hierarchy = cv2.findcontours(ref.copy(), cv2.retr_external, cv2.chain_approx_simple)
cv2.drawcontours(img, refcnts, -1, (0, 0, 255), 3)
cv_show('img', img)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_7.jpg", img)
# 轮廓排序
print(np.array(refcnts).shape) # 打印轮廓为 (10,)
refcnts = contours.sort_contours(refcnts, method='left-to=right')[0]
digits = {}
# 遍历每一个轮廓
for (i, c) in enumerate(refcnts):
# 计算外接矩形并且resize成合适大小
(x, y, w, h) = cv2.boundingrect(c)
roi = ref[y:y + h, x:x + w]
# resize一下合适的大小
roi = cv2.resize(roi, (57, 88))
# 每一个数字对应每一个模板
digits[i] = roi
# 初始化卷积核
rectkernel = cv2.getstructuringelement(cv2.morph_rect, (9, 3))
sqkernel = cv2.getstructuringelement(cv2.morph_rect, (5, 5))
# 读取输入图像,预处理
image = cv2.imread("d:\python\program\pythonproject\photos\p_8_0.png")
cv_show('image', image)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_8.jpg", image)
image = resize(image, width=300)
gray = cv2.cvtcolor(image, cv2.color_bgr2gray)
cv_show('gray', gray)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_9.jpg", gray)
# 礼帽操作,突出更明亮的区域
tophat = cv2.morphologyex(gray, cv2.morph_tophat, rectkernel)
cv_show('tophat', tophat)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_10.jpg", tophat)
# 梯度计算:根据字体的大小进行过滤
gradx = cv2.sobel(tophat, ddepth=cv2.cv_32f, dx=1, dy=0, ksize=-1) # ksize=-1相当于用3*3的
gradx = np.absolute(gradx)
(minval, maxval) = (np.min(gradx), np.max(gradx))
gradx = (255 * ((gradx - minval) / (maxval - minval)))
gradx = gradx.astype("uint8")
print(np.array(gradx).shape)
cv_show('gradx', gradx)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_11.jpg", gradx)
# 通过闭操作(先膨胀,再腐蚀)将数字连在一起
gradx = cv2.morphologyex(gradx, cv2.morph_close, rectkernel)
cv_show('gradx', gradx)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_12.jpg", gradx)
# thresh_otsu会【自动】寻找合适的阈值,适合双峰,需把阈值参数设置为0
thresh = cv2.threshold(gradx, 0, 255, cv2.thresh_binary | cv2.thresh_otsu)[1]
cv_show('thresh', thresh)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_13.jpg", thresh)
# 再来一个闭操作
thresh = cv2.morphologyex(thresh, cv2.morph_close, sqkernel) # 再来一个闭操作
cv_show('thresh', thresh)
# cv2.imwrite("d:\python\program\pythonproject\photos\p_14.jpg", thresh)
# 计算轮廓
threshcnts, hierarchy = cv2.findcontours(thresh.copy(), cv2.retr_external, cv2.chain_approx_simple)
cnts = threshcnts
cur_img = image.copy()
cv2.drawcontours(cur_img, cnts, -1, (0, 0, 255), 3)
cv_show('img', cur_img)
locs = []
cv2.imwrite("d:\python\program\pythonproject\photos\p_16.jpg", cur_img)
# 遍历轮廓
for (i, c) in enumerate(cnts):
# 计算矩形
(x, y, w, h) = cv2.boundingrect(c)
ar = w / float(h)
# 选择合适的区域,根据实际任务来,这里的基本都是四个数字一组
if ar > 2.5 and ar < 4.0:
if (w > 40 and w < 55) and (h > 10 and h < 20):
# 符合的留下来
locs.append((x, y, w, h))
# 将符合的轮廓从左到右排序
locs = sorted(locs, key=lambda x: x[0])
output = []
# 遍历每一个轮廓中的数字
for (i, (gx, gy, gw, gh)) in enumerate(locs):
# initialize the list of group digits
groupoutput = []
# 根据坐标提取每一个组
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)
# 计算每一组的轮廓
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) = 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.imwrite("d:\python\program\pythonproject\photos\p_17.jpg", image)
cv2.waitkey(0)
cv2.destroyallwindows()
发表评论