《案例》—— OpenCV 实现2B铅笔填涂的答题卡答案识别

一、案例介绍

  • 下面是一张使用2B铅笔填涂选项后的答题卡
    在这里插入图片描述
  • 使用OpenCV 中的各种方法进行真确答案识别,最终将正确填涂的答案用绿色圈出,错误的答案不圈出,用红色圈出错误题目的正确答案
  • 最终统计正确的题目数量,并在答题卡的左上角写出分数
  • 最终的结果图如下:
    在这里插入图片描述

二、代码解析

  • 先直接上完整代码

    import numpy as np
    import cv2
    
    """ 定义显示图片的函数 """
    
    
    def cv_show(name, img):
        cv2.imshow(name, img)
        cv2.waitKey(0)
    
    
    """ 寻找透视变换时的四个近似轮廓的顶点 """
    
    
    def order_points(pts):
        # 一共4个坐标
        rect = np.zeros((4, 2), dtype="float32")
    
        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
        # 计算输入的w和h值
        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)
        warped = cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    
        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))
        # zip(*...)使用星号操作符解包排序后的元组列表,并将其重新组合成两个列表:一个包含所有轮廓,另一个包含所有边界框。
        return cnts, boundingBoxes
    
    
    ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}  # 正确答案
    
    """ 图片预处理 """
    image = cv2.imread('images/test_01.png')  # 读取答题卡图片
    contours_img = image.copy()  # 复制一个原图为了后续的步骤在其上操作
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 转换为灰度图
    """ 高斯滤波 去除图片中的噪声点 """
    blurred = cv2.GaussianBlur(gray, (5, 5), 0)
    cv_show('blurred', blurred)  # 提前定义好的用于显示图片的函数 cv_show
    """ 边缘检测 """
    edged = cv2.Canny(blurred, 75, 200)
    cv_show('edged', edged)
    """ 轮廓检测 """
    cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
    cv2.drawContours(contours_img, cnts, -1, (0, 0, 255), 3)
    cv_show('contours_img', contours_img)
    
    """ 图像透视变换 --> 将答题卡区域提取出来 """
    docCnt = None
    # 根据轮廓大小进行排序,准备透视变换
    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
    
    # 执行透视变换
    warped_t = four_point_transform(image, docCnt.reshape(4, 2))  # 提前定义好的图像透视变换函数 four_point_transform
    warped_new = warped_t.copy()
    cv_show('warped', warped_t)
    # 转换为灰度图
    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)
    cv_show('warped_Contours', warped_Contours)
    
    questionCnts = []  # 用于存储正确的答案选项的轮廓
    for c in cnts:  # 遍历轮廓并计算比例和大小
        # 计算每个轮廓的外接矩阵的左上角坐标(x, y), 以及宽w高h的大小
        (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]  # 提前定义好的轮廓排序函数 sort_contours
    
    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掩膜来判断结果
            mask = np.zeros(thresh.shape, dtype="uint8")
            cv2.drawContours(mask, [c], -1, 255, -1)
            cv_show('mask', mask)
            # 通过计算非零点数量来算是否选择这个答案
            # 利用掩膜(mask)进行”与“操作,只保留mask位置中的内容
            thresh_mask_and = cv2.bitwise_and(thresh, thresh, mask=mask)
            cv_show('thresh_mask_and', thresh_mask_and)
            total = cv2.countNonZero(thresh_mask_and)  # 统计像素值不为0的像素数
            if bubbled is None or total > bubbled[0]:  # 通过阈值判断,保存灰度值最大的序号
                bubbled = (total, j)
        # 对比正确答案
        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('warped_new', warped_new)
    
    
    """ 统计得分,并在答题卡的左上角写上分数 """
    score = (correct / 5.0) * 100
    print("[INFO] score: {}分".format(score))
    cv2.putText(warped_new, "{}".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)
    
  • 步骤解析

    • 首先将每一题的正确答案的索引号与每一题的索引号对应上 ,以一个字典的形式保存在一个变量中

      ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
      
    • 1.图片预处理

      image = cv2.imread('images/test_01.png')    # 读取答题卡图片
      contours_img = image.copy()     # 复制一个原图为了后续的步骤在其上操作
      gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  # 转换为灰度图
      """ 高斯滤波 去除图片中的噪声点 """
      blurred = cv2.GaussianBlur(gray, (5, 5), 0)
      cv_show('blurred', blurred)  # 提前定义好的用于显示图片的函数 cv_show
      """ 边缘检测 """
      edged = cv2.Canny(blurred, 75, 200)
      cv_show('edged', edged)
      """ 轮廓检测 """
      cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
      cv2.drawContours(contours_img, cnts, -1, (0, 0, 255), 3)
      cv_show('contours_img', contours_img)
      
      • 效果如下:
        在这里插入图片描述
    • 2.将答题卡区域提取出来(图像透视变换),并进行处理

      """ 图像透视变换 --> 将答题卡区域提取出来 """
      docCnt = None
      # 根据轮廓大小进行排序,准备透视变换
      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
      
      # 执行透视变换
      warped_t = four_point_transform(image, docCnt.reshape(4, 2))  # 提前定义好的图像透视变换函数 four_point_transform
      warped_new = warped_t.copy()
      cv_show('warped', warped_t)
      # 转换为灰度图
      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()
      
      • 结果如下:
        在这里插入图片描述
    • 3.对答题卡中的每一个答案选项区域进行处理

      # 找到每一个圆圈轮廓
      cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[1]
      warped_Contours = cv2.drawContours(warped_t, cnts, -1, (0, 255, 0), 1)
      cv_show('warped_Contours', warped_Contours)
      
      questionCnts = []  # 用于存储正确的答案选项的轮廓
      for c in cnts:  # 遍历轮廓并计算比例和大小
          # 计算每个轮廓的外接矩阵的左上角坐标(x, y), 以及宽w高h的大小
          (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)
      
      • 结果如下:
        在这里插入图片描述
    • 4.将每个答案的轮廓按照答题卡上的顺序正确排序后,与正确答案进行比较

      # 先按照从上到下排序
      questionCnts = sort_contours(questionCnts, method="top-to-bottom")[0]  # 提前定义好的轮廓排序函数 sort_contours
      
      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掩膜来判断结果
              mask = np.zeros(thresh.shape, dtype="uint8")
              cv2.drawContours(mask, [c], -1, 255, -1)
              cv_show('mask', mask)
              # 通过计算非零点数量来算是否选择这个答案
              # 利用掩膜(mask)进行”与“操作,只保留mask位置中的内容
              thresh_mask_and = cv2.bitwise_and(thresh, thresh, mask=mask)
              cv_show('thresh_mask_and', thresh_mask_and)
              total = cv2.countNonZero(thresh_mask_and)  # 统计像素值不为0的像素数
              if bubbled is None or total > bubbled[0]:  # 通过阈值判断,保存灰度值最大的序号
                  bubbled = (total, j)
          # 对比正确答案
          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('warped_new', warped_new)
      
      • 其中部分展示效果如下:
        在这里插入图片描述
        在这里插入图片描述
      • 结果如下:
        在这里插入图片描述
    • 5.统计得分,并在答题卡的左上角写上分数

      """ 统计得分,并在答题卡的左上角写上分数 """
      score = (correct / 5.0) * 100
      print("[INFO] score: {}分".format(score))
      cv2.putText(warped_new, "{}".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)
      
      • 最终结果如下:
        在这里插入图片描述
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值