OpenCV答题卡识别

文章目录

OpenCV在答题卡识别中发挥着重要作用,它能够通过一系列图像处理技术,实现对答题卡的自动识别,并进行答题结果的统计。以下是一个基于OpenCV的答题卡识别的基本流程和关键步骤:

一、基本流程

  • 图片读取:首先,使用OpenCV读取答题卡的图像文件。
  • 图片预处理:对读取的图像进行预处理,包括灰度化、滤波去噪、边缘检测等,以突出答题卡中的关键信息。
  • 轮廓检测:通过轮廓检测算法,找到答题卡中各个选项或区域的轮廓。
  • 透视变换:对检测到的轮廓进行透视变换,以校正答题卡的视角,使其更加符合后续处理的需求。
  • 阈值处理:对校正后的图像进行阈值处理,将图像转换为二值图像,便于后续的分析和识别。
  • 答题区域识别:在二值图像中,识别出答题卡上的各个答题区域。
  • 答题结果判断:根据答题区域的填充情况,判断答题结果,并与正确答案进行对比,计算答题正确率。

二、代码实现

1.定义函数

python 复制代码
import numpy as np
import cv2

ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}


def cv_show(name, img):
    cv2.imshow(name, img)
    cv2.waitKey(60)


def order_points(pts):
    rect = np.zeros((4, 2), dtype='float32')  # 用来存储排序之后的坐标位置
    # 按顺序找到对应华标0123分别是左上,右上,右下,左下
    s = pts.sum(axis=1)
    rect[0] = pts[np.argmin(s)]
    rect[2] = pts[np.argmax(s)]
    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))
    maxWidth = 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))
    maxHeight = max(int(heightA), int(heightB))
    # 变换后对应坐标位置
    dst = np.array([[0, 0], [maxWidth - 1, 0],
                    [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]], dtype='float32')
    M = cv2.getPerspectiveTransform(rect, dst)  # 计算从原始四边形到目标矩形的透视变换矩阵 M。
    warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))  # 应用透视变换矩阵 M 到原始图像 image 上,对图像透视变换
    return warped


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]
    (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
                                        key=lambda b: b[1][i], reverse=reverse))
    return cnts, boundingBoxes

定义答案密钥:

  • ANSWER_KEY 是一个字典,存储了每个问题的正确答案(在这个例子中,只有5个问题,但密钥是通用的,可以扩展到更多问题)。

定义辅助函数:

  • cv_show(name, img):显示图像,并在指定时间后关闭窗口。
  • order_points(pts):根据轮廓点的坐标,将它们排序为左上、右上、右下、左下的顺序,以便进行透视变换。
  • four_point_transform(image, pts):使用四个点进行透视变换,将图像校正为矩形。
  • sort_contours(cnts,method='left-to-right'):根据指定的方法(从左到右、从右到左、从上到下、从下到上)对轮廓进行排序。

2.图像预处理

(1)高斯模糊、边缘检测

python 复制代码
image = cv2.imread(r'./images/test_01.png')
contours_img = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)  # 对图像进行高斯模糊
# (5,5)表示高斯核函数,决定模糊程度,越大越模糊,0表示自动计算标准差。
cv_show('blurred', blurred)
edged = cv2.Canny(blurred, 75, 200)  # 边缘检测
cv_show('edged', edged)

读取答题卡图像,将图像转换为灰度图,然后应用高斯模糊来减少噪声并使用Canny边缘检测来找到图像中的边缘。打印图片如下:

(2)轮廓检测

python 复制代码
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]  # cv2.RETR_EXTERNAL 轮廓检索,只检索最外层轮廓。
cv2.drawContours(contours_img, cnts, -1, (0, 0, 255), 3)  # 绘制轮廓,在contours_img中绘制检索的轮廓
cv_show('conyours_img', contours_img)
docCnt = None
cv2.waitKey(10000)

cnts = sorted(cnts, key=cv2.contourArea, reverse=True)  # 通过轮廓面积对轮廓进行由大到小排序
for c in cnts:
    peri = cv2.arcLength(c, True)  # 计算闭合轮廓的周长
    approx = cv2.approxPolyDP(c, 0.02 * peri, True)  # 对轮廓进行多边逼近

    if len(approx) == 4:  # 如果结果为四边形
        docCnt = approx
        break

在边缘检测后的图像中找到外部轮廓并进行绘制,根据轮廓面积对轮廓进行排序,找到最大的轮廓。使用approxPolyDP函数对轮廓进行多边形逼近,如果结果是四边形,则认为这是答题卡的轮廓。图像如下:

(3)透视变换

python 复制代码
warped_t = four_point_transform(image, docCnt.reshape(4, 2))  # 调用函数进行图像透视变换
warped_new = warped_t.copy()
cv_show('warped', warped_t)

调用上述定义的函数four_point_transform,使用找到的答题卡轮廓的四个角点进行透视变换,将答题卡校正为矩形。图像如下:

(4)阈值处理和轮廓检测

python 复制代码
warped = cv2.cvtColor(warped_t, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(warped, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] # 对图像进行阈值处理
cv_show('thresh', thresh)
thresh_Contours = thresh.copy()
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1] # 轮廓检测
warped_Contours = cv2.drawContours(warped_t, cnts, -1, (0, 255, 0), 1) # 在warped_t上绘制cnts轮廓
cv_show('warped_Contours', warped_Contours)
cv2.waitKey(10000)
questionCnts = []

对校正后的图像转化为灰度图,然后进行阈值处理,得到二值图像。在二值图像中再次进行轮廓检测,找到外部轮廓,这些轮廓代表答题卡上的选项。图像如下:

3.筛选和排序选项轮廓

python 复制代码
for c in cnts:
    (x, y, w, h) = cv2.boundingRect(c)
    ar = w / float(h)
    if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
        questionCnts.append(c)

questionCnts = sort_contours(questionCnts, method='top-to-bottom')[0] # 轮廓将按照它们在图像中从上到下的顺序进行排序。

根据轮廓的宽度、高度和宽高比筛选出类似矩形的轮廓,对选项轮廓进行排序,以便按顺序处理每个问题。

4.判断答案

python 复制代码
correct = 0
for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):
    cnts = sort_contours(questionCnts[i:i + 5])[0]
    bubbled = None
    for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype='uint8') # 创建一个与二值图像 thresh 形状相同、数据类型为 uint8 的全零数组作为掩码。
        cv2.drawContours(mask, [c], -1, 255, -1)
        cv_show('mask', mask)
        cv2.waitKey(10000)
        thresh_mask_and = cv2.bitwise_and(thresh, thresh, mask=mask) # 使用掩码对二值图像 thresh 进行按位与操作,得到只包含当前轮廓内部像素的图像。
        cv_show('thresh_mask_and', thresh_mask_and)
        total = cv2.countNonZero(thresh_mask_and) # 计算应用掩码后的图像中非零像素的总数。
        if bubbled is None or total > bubbled[0]:
            bubbled = (total, j)

    # 比较答案,通过将最多零像素总和的轮廓索引与答案索引比较,如果相同,及为绿色,且加入correct中,不同为红
    color = (0, 0, 255)
    k = ANSWER_KEY[q]

    if k == bubbled[1]:
        color = (0, 255, 0)
        correct += 1

    cv2.drawContours(warped_new, [cnts[k]], -1, color, 3)
    cv_show('warpeding', warped_new)

对上述筛选的轮廓结果进行分组,每5给为一组。创建掩码mask,对二值图像 thresh 进行按位与操作,得到只包含当前轮廓内部像素的图像。计算应用掩码后的图像中非零像素的总数。将选中的选项与正确答案进行比较,如果匹配,则增加正确计数。图像如下:

5.显示结果

python 复制代码
score = (correct / 5.0) * 100
print('[INFO] score: {:.2f}% '.format(score))
cv2.putText(warped_new, '{:.2f}%'.format(score), (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv2.imshow('Original', image)
cv2.imshow('Exam', warped_new)
cv2.waitKey(0)

在校正后的图像上用不同颜色标记出正确和错误的选项并计算并显示得分,显示原始图像和标记后的图像。

三、总结

本次主要为大家展示识别的答题卡的程序,这个程序的关键在于正确地识别答题卡的轮廓、选项的轮廓,以及准确地判断哪个选项被选中。通过这些操作,更好的为大家演示如何正确将轮廓检测、透视变换和阈值处理的结合使用。

相关推荐
用户600071819101 分钟前
【翻译】构建 Claude Code 的经验:我们如何使用 Skills
人工智能
没事别瞎琢磨4 分钟前
五、进程执行——spawn、超时与进程树清理
人工智能·node.js
没事别瞎琢磨7 分钟前
四、命令风险分级与审批策略
人工智能·node.js
阿乔外贸日记12 分钟前
埃塞俄比亚出口全流程注意事项
大数据·人工智能·智能手机·云计算·汽车
程序员cxuan17 分钟前
Agents.md 是什么
人工智能·后端·程序员
人工小情绪18 分钟前
Windows 安装 Codex 桌面版,并用 CC Switch 管理配置
人工智能·windows·codex·cc switch
godspeed_lucip21 分钟前
LLM和Agent——专题6:Multi Agent 入门(5)
人工智能·python
网安情报局22 分钟前
告别排队与高延迟:直连GPT全系列,解锁低门槛、高稳定的AI生产力
人工智能·gpt·api·ai大模型
Hali_Botebie23 分钟前
非共轭先验(Non-conjugate Prior)和共轭先验(Conjugate Prior)
人工智能·机器学习
没事别瞎琢磨32 分钟前
三、配置系统——默认值与解析
人工智能·node.js