#%%
import matplotlib.pyplot as plt
import cv2 as cv
import numpy as np
from imutils import contours
#%%
# 读取一个模板图像
img_num = cv.imread("...") # 数字模板图像地址
plt.imshow(img_num)
plt.title("img_num")
#%%
# 灰度图
img_num_gray = cv.cvtColor(img_num, cv.COLOR_BGR2GRAY)
plt.imshow(img_num_gray, cmap="gray")
plt.title("img_num_gray")
#%%
# 二值图像
img_num_thresh = cv.threshold(img_num_gray, 10, 255, cv.THRESH_BINARY_INV)[1]
plt.imshow(img_num_thresh, cmap="gray")
plt.title("img_num_thresh")
#%%
# 计算轮廓
# cv2.findContours()函数接受的参数为二值图,即黑白的(不是灰度图),cv2.RETR_EXTERNAL只检测外轮廓,cv2.CHAIN_APPROX_SIMPLE只保留终点坐标
# 返回的list中每个元素都是图像中的一个轮廓
img_num_conts, hierarchy= cv.findContours(img_num_thresh.copy(), cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
img_num_copy = cv.drawContours(img_num.copy(), img_num_conts, -1, (0,0,255), 2)
plt.imshow(img_num_copy[:,:,::-1])
plt.title("")
img_num_conts = contours.sort_contours(img_num_conts, method="left-to-right")[0] #排序,从左到右,从上到下
#%%
digits = {
}
# 遍历每一个轮廓
for(i,c) in enumerate(img_num_conts):
(x,y,w,h) = cv.boundingRect(c)
roi = img_num_thresh[y:y + h, x:x + w]
roi = cv.resize(roi, (57, 88))
python实现卡号识别
最新推荐文章于 2024-01-19 15:17:23 发布
该文详细描述了一种利用OpenCV进行数字图像处理的方法,包括图像读取、灰度化、二值化、轮廓检测、数字模板匹配等步骤,最终实现对输入图像中数字的识别。

最低0.47元/天 解锁文章
3161

被折叠的 条评论
为什么被折叠?



