项目思路:
- 图片预处理.
- 透视变换, 把答题卡的视角拉正.
- 找圆圈的轮廓
- 对圆圈轮廓排序
- 通过计算非零值来判断是否答题正确.
图片预处理
import numpy as np
import cv2
# 封装展示函数
def cv_show(name, img):
cv2.imshow(name, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)
# 读图片
img = cv2.imread('./images/test_01.png')
cv_show('img', img)
# 灰度化
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 高斯滤波,去掉一些噪点
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
cv_show('blurred', blurred)
# 边缘检测,canny算法
edged = cv2.Canny(blurred, 75, 200)
cv_show('edged', edged)
# 利用边缘,检测轮廓并返回
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
# 画轮廓会修改被画轮廓的图,提前进行拷贝
contours_img = img.copy()
# 在拷贝图上,画轮廓
cv2.drawContours(contours_img, cnts, -1, (0, 0, 255), 3)
cv_show('contous_img', contours_img)
# 确保我们拿到的轮廓是答题卡的轮廓.
if len(cnts) > 0:
# 根据轮廓面积对轮廓进行排序.
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# 遍历每一个轮廓
for c in cnts:
# 计算周长
perimeter = cv2.arcLength(c, True)
# 利用多边形近似,得到近似的轮廓
approx = cv2.approxPolyDP(c, 0.02 * perimeter, True)
# 近似完了之后, 应该只剩下4个角的坐标.
if len(approx) == 4:
# 保存approx
docCnt = approx
# 找到答题卡近似轮廓, 直接推荐.
break
docCnt
array([[[131, 206]], [[119, 617]], [[448, 614]], [[430, 208]]], dtype=int32)
透视变换
# 生成随机矩阵
a = np.random.randint(0, 10, size=(4, 4))
a
array([[4, 4, 5, 8], [8, 3, 7, 5], [5, 7, 0, 2], [0, 3, 1, 2]])
np.diff() 沿着指定轴计算第N维的离散差值
参数:
- a:输入矩阵
- n:可选,代表要执行几次差值
# 计算离散差值
np.diff(a, axis=1)
array([[ 0, 1, 3], [-5, 4, -2], [ 2, -7, 2], [ 3, -2, 1]])
# 进行透视变换.
# 透视变换要找到变换矩阵.
# 变换矩阵要求原图的4个点坐标和变换之后的4个点坐标.
# 现在已经找到了原图的4个点坐标. 需要找到变换之后的4个坐标.
# 先对获取到的4个角点坐标按照一定顺序(顺时针, 或逆时针)排序
# 排序功能是一个独立功能, 可以封装成一个函数 -- 传入变换前的角点坐标
def order_points(pts):
# 创建全是0的矩阵, 来接收等下找出来的4个角的坐标.
rect = np.zeros((4, 2), dtype='float32')
s = pts.sum(axis=1)
# 左上的坐标一定是x,y加起来最小的坐标. 右下的坐标一定是x,y加起来最大的坐标.
rect[0] = pts[np.argmin(s)]
rect[2] = pts[np.argmax(s)]
# 右上角的x,y相减的差值一定是最小的.
# 左下角的x,y相减的差值, 一定是最大.
diff = np.diff(pts, axis=1)
rect[1] = pts[np.argmin(diff)]
rect[3] = pts[np.argmax(diff)]
return rect
# 把透视变换功能封装成一个函数
def four_point_transform(image, pts):
# 获取原图中,排序好的四个角点
rect = order_points(pts)
(tl, tr, br, bl) = rect
# 计算变换之后,图的宽高
widthA = np.sqrt((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)
widthB = np.sqrt((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)
max_width = max(int(widthA), int(widthB))
heightA = np.sqrt((tr[0] - br[0]) ** 2 + (tr[1] - br[1]) ** 2)
heightB = np.sqrt((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)
max_height = max(int(heightA), int(heightB))
# 构造变换之后的角点坐标位置.
dst = np.array([
[0, 0],
[max_width - 1, 0],
[max_width - 1, max_height - 1],
[0, max_height - 1]], dtype='float32')
# 计算变换矩阵
M = cv2.getPerspectiveTransform(rect, dst)
# 透视变换
warped = cv2.warpPerspective(image, M, (max_width, max_height))
return warped
# 进行透视变换
warped = four_point_transform(img, docCnt.reshape(4, 2))
cv_show('warped', warped)
找圆圈的轮廓
# 二值化
thresh = cv2.threshold(warped, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv_show('thresh', thresh)
# 找到每一个圆圈的轮廓
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[0]
# 对二值化图像拷贝 -- 方便绘图,不改变原来二值化图像
thresh_contours = thresh.copy()
# 绘制轮廓
cv2.drawContours(thresh_contours, cnts, -1, 255, 3)
cv_show('thresh_contours', thresh_contours)
import matplotlib.pyplot as plt
plt.imshow(thresh_contours, cmap='gray')
# 遍历所有的轮廓, 找到特定宽高和特定比例的轮廓, 即圆圈的轮廓.
question_cnts = [] # 存储圆圈的轮廓
for c in cnts:
# 找到轮廓的外接矩形
(x, y, w, h) = cv2.boundingRect(c)
# 计算宽高比
ar = w / float(h)
# 根据实际情况制定标准.
if w >= 20 and h >= 20 and 0.9 <= ar <= 1.1:
question_cnts.append(c)
len(question_cnts)
25
对圆圈轮廓排序
# 轮廓排序功能封装成函数
def sort_contours(cnts, method='left-to-right'):
reverse = False
# 排序的时候, 取x轴数据, i=0, 取y轴数据i =1
i = 0
if method == 'right-to-left' or method == 'bottom-to-top':
reverse = True
# 按y轴坐标排序
if method == 'top-to-bottom' or method == 'bottom-to-top':
i = 1
# 计算每个轮廓的外接矩形
bounding_boxes = [cv2.boundingRect(c) for c in cnts]
(cnts, bounding_boxes) = zip(*sorted(zip(cnts, bounding_boxes), key=lambda b: b[1][i], reverse=reverse))
return cnts, bounding_boxes
# 按照从上到下的顺序,对question_cnts排序.
question_cnts = sort_contours(question_cnts, method='top-to-bottom')[0]
判断是否答题正确
# 正确答案
ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
# 记录答对的题数
correct = 0
# 一共25个选项,5道题
for (q, i) in enumerate(np.arange(0, 25, 5)):
# 每次取出5个轮廓, 再按照x轴坐标从小到大排序
cnts = sort_contours(question_cnts[i: i + 5])[0]
# 记录一题的选项
bubbled = None
# 遍历每一个结果
for (j, c) in enumerate(cnts):
# 使用掩膜, 即mask
mask = np.zeros(thresh.shape, dtype='uint8')
# 在掩膜上,画圆圈轮廓,并填充内部区域
cv2.drawContours(mask, [c], -1, 255, -1)
# 先做与运算
mask = cv2.bitwise_and(thresh, thresh, mask=mask)
# 计算非零个数, 选择的选项, 非零个数比较多, 没选中的选项非零个数少一些
total = cv2.countNonZero(mask)
if bubbled is None or total > bubbled[0]:
bubbled = (total, j)
color = (0, 0, 255)
k = ANSWER_KEY[q] # 该题的正确选项
# 判断是否做题正确
if k == bubbled[1]:
correct += 1
color = (0, 255, 0)
# 绘图
cv2.drawContours(warped, [cnts[k]], -1, color, 3)
# 计算分数
score = (correct / 5.0) * 100
print(f'score: {score:.2f}%')
cv2.putText(warped, str(score) + '%', (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv_show('result', warped)
score: 80.00%