当前位置: 首页 > article >正文

OpenCV答题卡识别

文章目录

  • 一、基本流程
  • 二、代码实现
    • 1.定义函数
    • 2.图像预处理
      • (1)高斯模糊、边缘检测
      • (2)轮廓检测
      • (3)透视变换
      • (4)阈值处理和轮廓检测
    • 3.筛选和排序选项轮廓
    • 4.判断答案
    • 5.显示结果
  • 三、总结

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

一、基本流程

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

二、代码实现

1.定义函数

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)高斯模糊、边缘检测

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)轮廓检测

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)透视变换

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

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

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

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.筛选和排序选项轮廓

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.判断答案

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.显示结果

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)

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

三、总结

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


http://www.kler.cn/news/358121.html

相关文章:

  • 数据结构与算法JavaScript描述练习------第13章检索算法
  • Oracle NUMTODSINTERVAL函数和区间函数
  • 大厂面试提问:Flash Attention 是怎么做到又快又省显存的?
  • java maven
  • C++多款质量游戏及开发建议[OIER建议]
  • Redis和Jedis的区别
  • 软件测试学习笔记丨接口自动化测试-接口请求
  • 无人机:无线电波控制技术!
  • vue2鼠标左划、右划(左滑、右滑)时间
  • 从0开始深度学习(12)——多层感知机的逐步实现
  • RHCE第一次笔记
  • 【机器学习】深入浅出讲解贝叶斯分类算法
  • poisson过程——随机模拟(Python和R实现)
  • Element-ui官方示例(Popover 弹出框)
  • 微信小程序应用echarts和二维表的结合
  • 动态规划-子数组系列——乘积最大子数组
  • 【面试11】嵌入式之模电/数电
  • setState更新状态的2种写法
  • 高级算法设计与分析 学习笔记14 FFT
  • Axure科技感元件:打造可视化大屏设计的得力助手