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

《案例》—— 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 = Falsei = 0if method == 'right-to-left' or method == 'bottom-to-top':reverse = Trueif method == 'top-to-bottom' or method == 'bottom-to-top':i = 1boundingBoxes = [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, boundingBoxesANSWER_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 = approxbreak# 执行透视变换
    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_contourscorrect = 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.图片预处理

      • 图像边缘检测的介绍:https://blog.csdn.net/weixin_73504499/article/details/141832066?spm=1001.2014.3001.5501
      • 图像轮廓检测的介绍:https://blog.csdn.net/weixin_73504499/article/details/141873522?spm=1001.2014.3001.5501
      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.将答题卡区域提取出来(图像透视变换),并进行处理

      • 透视变换的两个关键函数的解析:https://blog.csdn.net/weixin_73504499/article/details/142864082?spm=1001.2014.3001.5501
      """ 图像透视变换 --> 将答题卡区域提取出来 """
      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 = approxbreak# 执行透视变换
      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_contourscorrect = 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)
      
      • 最终结果如下:
        在这里插入图片描述
http://www.lryc.cn/news/463115.html

相关文章:

  • 新员工入职流程指南_完整入职流程解析
  • mysql查看和修改默认配置
  • 海外云手机:出海电商养号智能化方案
  • OpenAI Canvas用户反馈:并不如外界传言般“炸裂”,更不是“AGI的终极交互形态” | LeetTalk Daily...
  • RiproV9.0主题wordpress主题免扩展可二开PJ版/WordPress博客主题Ripro全解密无后门版本
  • [LeetCode] 515. 在每个树行中找最大值
  • 【分布式微服务云原生】《微服务架构大揭秘:流行框架与服务治理攻略》
  • uniapp uni.uploadFile errMsg: “uploadFile:fail
  • 一个常见问题:TCP和UDP是否可以使用一个端口
  • 前端报错:‘vue-cli-service‘ 不是内部或外部命令,也不是可运行的程序(node_modules下载不下来)
  • 白日门【鬼服无限刀】win服务端+安卓客户端+教程+GM后台
  • 如何迅速的了解一个人
  • Window和Linux远程调度kettle
  • 设定义结构变量
  • SSD |(七)FTL详解(中)
  • Swift 协议:深入解析与高级应用
  • API项目3:API签名认证
  • unity学习-Directional light光的设置
  • 简单实现通过电脑操作手机
  • 基于ESP32的便携式游戏机
  • 【LeetCode 88. 合并两个有序数组】 java实现
  • 200Kg大载重多旋无人机价格高昂技术分析
  • 快速理解http的get和post
  • Mamba学习笔记(3)—S4原理基础
  • 好看的ppt字体推荐!分享3个制作幻灯片的常用软件!
  • 第6篇:无线与移动网络
  • 【C++标准模版库】unordered_map和unordered_set的介绍及使用
  • 深度解析Transformer:从自注意力到MLP的工作机制
  • 《米小圈动画成语》|在趣味中学习,在快乐中掌握成语知识!
  • linux系统之jar启动脚本