使用 OpenCV-Python 识别答题卡判卷功能

 更新时间:2021年12月21日 15:08:03   作者:糖公子没来过  
这篇文章主要介绍了使用 OpenCV-Python 识别答题卡判卷,本文分步骤通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

任务

识别用相机拍下来的答题卡,并判断最终得分(假设正确答案是B, E, A, D, B)

主要步骤

  1. 轮廓识别——答题卡边缘识别
  2. 透视变换——提取答题卡主体
  3. 轮廓识别——识别出所有圆形选项,剔除无关轮廓
  4. 检测每一行选择的是哪一项,并将结果储存起来,记录正确的个数
  5. 计算最终得分并在图中标注

分步实现

轮廓识别——答题卡边缘识别

输入图像

import cv2 as cv
import numpy as np
 
# 正确答案
right_key = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
 
# 输入图像
img = cv.imread('./images/test_01.jpg')
img_copy = img.copy()
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cvshow('img-gray', img_gray)

图像预处理

# 图像预处理
# 高斯降噪
img_gaussian = cv.GaussianBlur(img_gray, (5, 5), 1)
cvshow('gaussianblur', img_gaussian)
# canny边缘检测
img_canny = cv.Canny(img_gaussian, 80, 150)
cvshow('canny', img_canny)

 

 

轮廓识别——答题卡边缘识别

# 轮廓识别——答题卡边缘识别
cnts, hierarchy = cv.findContours(img_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img_copy, cnts, -1, (0, 0, 255), 3)
cvshow('contours-show', img_copy)

透视变换——提取答题卡主体

对每个轮廓进行拟合,将多边形轮廓变为四边形

docCnt = None
 
# 确保检测到了
if len(cnts) > 0:
    # 根据轮廓大小进行排序
    cnts = sorted(cnts, key=cv.contourArea, reverse=True)
 
    # 遍历每一个轮廓
    for c in cnts:
        # 近似
        peri = cv.arcLength(c, True)
        # arclength 计算一段曲线的长度或者闭合曲线的周长;
        # 第一个参数输入一个二维向量,第二个参数表示计算曲线是否闭合
 
        approx = cv.approxPolyDP(c, 0.02 * peri, True)
        # 用一条顶点较少的曲线/多边形来近似曲线/多边形,以使它们之间的距离<=指定的精度;
        # c是需要近似的曲线,0.02*peri是精度的最大值,True表示曲线是闭合的
 
        # 准备做透视变换
        if len(approx) == 4:
            docCnt = approx
            break

透视变换——提取答题卡主体

# 透视变换——提取答题卡主体
docCnt = docCnt.reshape(4, 2)
warped = four_point_transform(img_gray, docCnt)
cvshow('warped', warped)
def four_point_transform(img, four_points):
    rect = order_points(four_points)
    (tl, tr, br, bl) = rect
 
    # 计算输入的w和h的值
    widthA = np.sqrt((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)
    widthB = np.sqrt((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)
    maxWidth = max(int(widthA), int(widthB))
 
    heightA = np.sqrt((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)
    heightB = np.sqrt((tr[0] - br[0]) ** 2 + (tr[1] - br[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')
 
    # 最主要的函数就是 cv2.getPerspectiveTransform(rect, dst) 和 cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    M = cv.getPerspectiveTransform(rect, dst)
    warped = cv.warpPerspective(img, M, (maxWidth, maxHeight))
    return warped
 
 
def order_points(points):
    res = np.zeros((4, 2), dtype='float32')
    # 按照从前往后0,1,2,3分别表示左上、右上、右下、左下的顺序将points中的数填入res中
 
    # 将四个坐标x与y相加,和最大的那个是右下角的坐标,最小的那个是左上角的坐标
    sum_hang = points.sum(axis=1)
    res[0] = points[np.argmin(sum_hang)]
    res[2] = points[np.argmax(sum_hang)]
 
    # 计算坐标x与y的离散插值np.diff()
    diff = np.diff(points, axis=1)
    res[1] = points[np.argmin(diff)]
    res[3] = points[np.argmax(diff)]
 
    # 返回result
    return res

轮廓识别——识别出选项

# 轮廓识别——识别出选项
thresh = cv.threshold(warped, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]
cvshow('thresh', thresh)
thresh_cnts, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
w_copy = warped.copy()
cv.drawContours(w_copy, thresh_cnts, -1, (0, 0, 255), 2)
cvshow('warped_contours', w_copy)
 
questionCnts = []
# 遍历,挑出选项的cnts
for c in thresh_cnts:
    (x, y, w, h) = cv.boundingRect(c)
    ar = w / float(h)
    # 根据实际情况指定标准
    if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
        questionCnts.append(c)
 
# 检查是否挑出了选项
w_copy2 = warped.copy()
cv.drawContours(w_copy2, questionCnts, -1, (0, 0, 255), 2)
cvshow('questionCnts', w_copy2)

成功将无关轮廓剔除

检测每一行选择的是哪一项,并将结果储存起来,记录正确的个数

# 检测每一行选择的是哪一项,并将结果储存在元组bubble中,记录正确的个数correct
# 按照从上到下t2b对轮廓进行排序
questionCnts = sort_contours(questionCnts, method="t2b")[0]
correct = 0
# 每行有5个选项
for (i, q) in enumerate(np.arange(0, len(questionCnts), 5)):
    # 排序
    cnts = sort_contours(questionCnts[q:q+5])[0]
 
    bubble = None
    # 得到每一个选项的mask并填充,与正确答案进行按位与操作获得重合点数
    for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype='uint8')
        cv.drawContours(mask, [c], -1, 255, -1)
        # cvshow('mask', mask)
 
        # 通过按位与操作得到thresh与mask重合部分的像素数量
        bitand = cv.bitwise_and(thresh, thresh, mask=mask)
        totalPixel = cv.countNonZero(bitand)
 
        if bubble is None or bubble[0] < totalPixel:
            bubble = (totalPixel, j)
 
    k = bubble[1]
    color = (0, 0, 255)
    if k == right_key[i]:
        correct += 1
        color = (0, 255, 0)
 
    # 绘图
    cv.drawContours(warped, [cnts[right_key[i]]], -1, color, 3)
    cvshow('final', warped)
def sort_contours(contours, method="l2r"):
    # 用于给轮廓排序,l2r, r2l, t2b, b2t
    reverse = False
    i = 0
    if method == "r2l" or method == "b2t":
        reverse = True
    if method == "t2b" or method == "b2t":
        i = 1
 
    boundingBoxes = [cv.boundingRect(c) for c in contours]
    (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes), key=lambda a: a[1][i], reverse=reverse))
    return contours, boundingBoxes

 

用透过mask的像素的个数来判断考生选择的是哪个选项

计算最终得分并在图中标注

# 计算最终得分并在图中标注
score = (correct / 5.0) * 100
print(f"Score: {score}%")
cv.putText(warped, f"Score: {score}%", (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv.imshow("Original", img)
cv.imshow("Exam", warped)
cv.waitKey(0)

完整代码

import cv2 as cv
import numpy as np
 
 
def cvshow(name, img):
    cv.imshow(name, img)
    cv.waitKey(0)
    cv.destroyAllWindows()
 
def four_point_transform(img, four_points):
    rect = order_points(four_points)
    (tl, tr, br, bl) = rect
 
    # 计算输入的w和h的值
    widthA = np.sqrt((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)
    widthB = np.sqrt((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)
    maxWidth = max(int(widthA), int(widthB))
 
    heightA = np.sqrt((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)
    heightB = np.sqrt((tr[0] - br[0]) ** 2 + (tr[1] - br[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')
 
    # 最主要的函数就是 cv2.getPerspectiveTransform(rect, dst) 和 cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    M = cv.getPerspectiveTransform(rect, dst)
    warped = cv.warpPerspective(img, M, (maxWidth, maxHeight))
    return warped
 
 
def order_points(points):
    res = np.zeros((4, 2), dtype='float32')
    # 按照从前往后0,1,2,3分别表示左上、右上、右下、左下的顺序将points中的数填入res中
 
    # 将四个坐标x与y相加,和最大的那个是右下角的坐标,最小的那个是左上角的坐标
    sum_hang = points.sum(axis=1)
    res[0] = points[np.argmin(sum_hang)]
    res[2] = points[np.argmax(sum_hang)]
 
    # 计算坐标x与y的离散插值np.diff()
    diff = np.diff(points, axis=1)
    res[1] = points[np.argmin(diff)]
    res[3] = points[np.argmax(diff)]
 
    # 返回result
    return res
 
 
def sort_contours(contours, method="l2r"):
    # 用于给轮廓排序,l2r, r2l, t2b, b2t
    reverse = False
    i = 0
    if method == "r2l" or method == "b2t":
        reverse = True
    if method == "t2b" or method == "b2t":
        i = 1
 
    boundingBoxes = [cv.boundingRect(c) for c in contours]
    (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes), key=lambda a: a[1][i], reverse=reverse))
    return contours, boundingBoxes
 
# 正确答案
right_key = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
 
# 输入图像
img = cv.imread('./images/test_01.jpg')
img_copy = img.copy()
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cvshow('img-gray', img_gray)
 
# 图像预处理
# 高斯降噪
img_gaussian = cv.GaussianBlur(img_gray, (5, 5), 1)
cvshow('gaussianblur', img_gaussian)
# canny边缘检测
img_canny = cv.Canny(img_gaussian, 80, 150)
cvshow('canny', img_canny)
 
# 轮廓识别——答题卡边缘识别
cnts, hierarchy = cv.findContours(img_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img_copy, cnts, -1, (0, 0, 255), 3)
cvshow('contours-show', img_copy)
 
docCnt = None
 
# 确保检测到了
if len(cnts) > 0:
    # 根据轮廓大小进行排序
    cnts = sorted(cnts, key=cv.contourArea, reverse=True)
 
    # 遍历每一个轮廓
    for c in cnts:
        # 近似
        peri = cv.arcLength(c, True)  # arclength 计算一段曲线的长度或者闭合曲线的周长;
        # 第一个参数输入一个二维向量,第二个参数表示计算曲线是否闭合
 
        approx = cv.approxPolyDP(c, 0.02 * peri, True)
        # 用一条顶点较少的曲线/多边形来近似曲线/多边形,以使它们之间的距离<=指定的精度;
        # c是需要近似的曲线,0.02*peri是精度的最大值,True表示曲线是闭合的
 
        # 准备做透视变换
        if len(approx) == 4:
            docCnt = approx
            break
 
 
# 透视变换——提取答题卡主体
docCnt = docCnt.reshape(4, 2)
warped = four_point_transform(img_gray, docCnt)
cvshow('warped', warped)
 
 
# 轮廓识别——识别出选项
thresh = cv.threshold(warped, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]
cvshow('thresh', thresh)
thresh_cnts, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
w_copy = warped.copy()
cv.drawContours(w_copy, thresh_cnts, -1, (0, 0, 255), 2)
cvshow('warped_contours', w_copy)
 
questionCnts = []
# 遍历,挑出选项的cnts
for c in thresh_cnts:
    (x, y, w, h) = cv.boundingRect(c)
    ar = w / float(h)
    # 根据实际情况指定标准
    if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
        questionCnts.append(c)
 
# 检查是否挑出了选项
w_copy2 = warped.copy()
cv.drawContours(w_copy2, questionCnts, -1, (0, 0, 255), 2)
cvshow('questionCnts', w_copy2)
 
 
# 检测每一行选择的是哪一项,并将结果储存在元组bubble中,记录正确的个数correct
# 按照从上到下t2b对轮廓进行排序
questionCnts = sort_contours(questionCnts, method="t2b")[0]
correct = 0
# 每行有5个选项
for (i, q) in enumerate(np.arange(0, len(questionCnts), 5)):
    # 排序
    cnts = sort_contours(questionCnts[q:q+5])[0]
 
    bubble = None
    # 得到每一个选项的mask并填充,与正确答案进行按位与操作获得重合点数
    for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype='uint8')
        cv.drawContours(mask, [c], -1, 255, -1)
        cvshow('mask', mask)
 
        # 通过按位与操作得到thresh与mask重合部分的像素数量
        bitand = cv.bitwise_and(thresh, thresh, mask=mask)
        totalPixel = cv.countNonZero(bitand)
 
        if bubble is None or bubble[0] < totalPixel:
            bubble = (totalPixel, j)
 
    k = bubble[1]
    color = (0, 0, 255)
    if k == right_key[i]:
        correct += 1
        color = (0, 255, 0)
 
    # 绘图
    cv.drawContours(warped, [cnts[right_key[i]]], -1, color, 3)
    cvshow('final', warped)
 
 
# 计算最终得分并在图中标注
score = (correct / 5.0) * 100
print(f"Score: {score}%")
cv.putText(warped, f"Score: {score}%", (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv.imshow("Original", img)
cv.imshow("Exam", warped)
cv.waitKey(0)
 
 

到此这篇关于使用 OpenCV-Python 识别答题卡判卷的文章就介绍到这了,更多相关OpenCV Python 识别答题卡判卷内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Python数据处理pandas读写操作IO工具CSV解析

    Python数据处理pandas读写操作IO工具CSV解析

    这篇文章主要为大家介绍了Python pandas数据读写操作IO工具之CSV使用示例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-06-06
  • 分享10个有趣的Python程序

    分享10个有趣的Python程序

    这篇文章主要给大家分享的是10个有趣的Python程序,Python程序有许多模块和第三方包,这非常有助于高效编程,所以了解这些模块的正确使用方法是很重要的,下面详细内容,需要的小伙伴可以参考一下
    2022-02-02
  • 简单谈谈Python中的json与pickle

    简单谈谈Python中的json与pickle

    下面小编就为大家带来一篇简单谈谈Python中的json与pickle。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • python学习之SpaCy库的高级特性详解

    python学习之SpaCy库的高级特性详解

    在之前的文章中,我们介绍了SpaCy库的一些基本概念和功能,在这篇文章中,我们将深入学习一些更高级的特性,包括词向量、依赖性解析、和自定义组件
    2023-07-07
  • Python wxPython库使用wx.ListBox创建列表框示例

    Python wxPython库使用wx.ListBox创建列表框示例

    这篇文章主要介绍了Python wxPython库使用wx.ListBox创建列表框,结合实例形式分析了wxPython库使用wx.ListBox创建列表框的简单实现方法及ListBox函数相关选项的功能,需要的朋友可以参考下
    2018-09-09
  • django2.0扩展用户字段示例

    django2.0扩展用户字段示例

    今天小编就为大家分享一篇关于django2.0扩展用户字段示例,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
    2019-02-02
  • 关于keras中的Reshape用法

    关于keras中的Reshape用法

    这篇文章主要介绍了关于keras中的Reshape用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2022-07-07
  • 浅谈Django自定义模板标签template_tags的用处

    浅谈Django自定义模板标签template_tags的用处

    这篇文章主要介绍了浅谈Django自定义模板标签template_tags的用处,具有一定借鉴价值,需要的朋友可以参考下。
    2017-12-12
  • 详解python项目实战:模拟登陆CSDN

    详解python项目实战:模拟登陆CSDN

    这篇文章主要介绍了python项目实战:模拟登陆CSDN,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-04-04
  • python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

    python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解

    下面小编就为大家带来一篇python爬虫 正则表达式使用技巧及爬取个人博客的实例讲解。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-10-10

最新评论