欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-06-28 23:26:15
任务识别用相机拍下来的答题卡,并判断最终得分(假设正确答案是b, e, a, d, b)主要步骤 轮廓识别——答题卡边缘识别 透视变换——提取答题卡主体 轮廓识别——识别出所有圆形选...

任务

识别用相机拍下来的答题卡,并判断最终得分(假设正确答案是b, e, a, d, b)

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

主要步骤

  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)

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

图像预处理

# 图像预处理
# 高斯降噪
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)

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

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

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

# 轮廓识别——答题卡边缘识别
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)

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

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

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

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

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

轮廓识别——识别出选项

# 轮廓识别——识别出选项
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)

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

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

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

成功将无关轮廓剔除

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

# 检测每一行选择的是哪一项,并将结果储存在元组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

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

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

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

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

# 计算最终得分并在图中标注
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 识别答题卡判卷功能

完整代码

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 识别答题卡判卷内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!