答题卡识别项目实战

答题卡识别效果

在这里插入图片描述
【大致思路】:先进行仿射变换去除背景(只留试卷部分),二值化,圆形轮廓检测,遍历每一行选项,统计非零像素,记录填充选项(即非零像素最多的轮廓区域),与正确答案进行比对,正确则correct数+1,得到总成绩
1-4 基础操作+透视变换

1-4是基础操作, 3是做近似变换, 取最大的那个轮廓,最有可能是图像最大外围的轮廓

3的近似变换 和 4的透视变换原理 可以参考我的 OCR文档扫描实战

# 1.预处理
image = cv2.imread(args["image"])
contours_img = image.copy()
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
cv_show('blurred',blurred)
edged = cv2.Canny(blurred, 75, 200)
cv_show('edged',edged)

# 2.轮廓检测
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

# 3.确保检测到了
if len(cnts) > 0:
	# 根据轮廓大小进行排序
	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

# 4.执行透视变换
warped = four_point_transform(gray, docCnt.reshape(4, 2))
cv_show('warped',warped)
在这里插入图片描述

5-6 阈值处理+轮廓检测

5.Otsu’s 阈值处理
THRESH_OTSU会自动寻找合适的阈值,适合双峰,需把阈值参数设置为0
在我的信用卡数字识别案例中出现也有应用(第三、五部分)

在这里插入图片描述

6.然后怎么区分涂和没涂的圆?
这里不用霍夫变换,因为有些涂完后 会突出边界,如下

# 5.Otsu's 阈值处理
thresh = cv2.threshold(warped, 0, 255,
	cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] 
cv_show('thresh',thresh)

thresh_Contours = thresh.copy()
# 6.找到每一个圆圈轮廓
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
	cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(thresh_Contours,cnts,-1,(0,0,255),3) 
cv_show('thresh_Contours',thresh_Contours)
questionCnts = []
在这里插入图片描述

7-8 筛选答题圈

7.遍历所有圆圈轮廓(包括干扰项) 筛选出答题区域的圆,其轮廓存于questionCnts
无论是圆形还是矩形的答题卡,都是规则的形状,比例相同.
所以这里要人工设定圆圈外接矩形的长宽比例
参考信用卡数字识别 (第四部分)

8.按照从上到下(从左到右)进行排序
参考信用卡数字识别 (第二部分)

# 7.遍历所有圆圈轮廓(包括干扰项) 筛选出答题区域的圆
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)

# 8.按照从上到下进行排序
questionCnts = sort_contours(questionCnts,
	method="top-to-bottom")[0]
correct = 0

9.每行的5个选项 分别比对正确答案

答题圈的轮廓questionCnts长度应为25, 间隔5, 可以遍历5次, 则
q 取0 1 2 3 4,共5行;
i 表示从第几个轮廓开始:0,5,10,15,20. 即每行的第一个轮廓

9.每行的5个选项 分别比对正确答案

for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):
# 9.1排序
cnts = sort_contours(questionCnts[i:i + 5])[0]
bubbled = None

# 9.2 遍历每一个结果
for (j, c) in enumerate(cnts):
    # 9.2.1 使用mask来判断结果
    mask = np.zeros(thresh.shape, dtype="uint8")
    cv2.drawContours(mask, [c], -1, 255, -1) #-1表示填充
    cv_show('mask',mask)
    # 9.2.2 通过计算非零点数量来算是否选择这个答案
    mask = cv2.bitwise_and(thresh, thresh, mask=mask)
    total = cv2.countNonZero(mask)

    # 9.2.3 通过阈值判断
    if bubbled is None or total > bubbled[0]:
        bubbled = (total, j)

# 9.3 获取正确答案
color = (0, 0, 255)
k = ANSWER_KEY[q]

# 9.4 对比答案 并 判断正确
if k == bubbled[1]:
    color = (0, 255, 0)
    correct += 1

# 9.5 绘图
cv2.drawContours(warped, [cnts[k]], -1, color, 3)

9.1 确保每一行的顺序为A B C D E
9.2 同样这么一行里,这5个框有什么不同.

j 取每个选项0 1 2 3 4
9.2.1 使用mask来判断结果

初始化一个 跟透视变换后的图 一样大小的mask(全黑)
然后在mask上, 画出当前遍历的这个(圆圈)轮廓c, 画成白色

cv2.drawContours (传入绘制图像,轮廓,轮廓索引,颜色模式,线条厚度)
参考OpenCV基本操作
补充一点:线条厚度 为负值或CV_FILLED 表示填充轮廓内部

一行遍历5个选项,5行一共25个选项,这展示前两行的遍历结果,后三行同理…

在这里插入图片描述

9.2.2 与操作

一张图片 跟 一张相同大小的黑白图片 进行与操作,则只保留图片的白色区域

cv2.bitwise_and(src1, src2, dst=None, mask=None)
对图像(灰度图像或彩色图像均可)每个像素值进行二进制“与”操作,
1&1=1,1&0=0,0&1=0,0&0=0

函数返回值: 调用时若无mask参数 则返回src1 & src2,若存在mask参数,则返回src1 & src2 & mask

    src1:输入原图1
    src2:输入原图2, src1与src2可以相同也可以不相同,可以是灰度图像也可以是彩色图像
    dst:输出矩阵,和输入矩阵一样的尺寸和类型 若存在参数时:src1 & src2 或者 src1 & src2 & mask
    mask:可以是单通道8bit灰度图像,也可以是矩阵,一般为二值化后的图像,指定要更改的输出数组的元素

cv2.countNonZero统计非零像素点个数

9.2.3 依次判断5个选项的哪个非零值最大(即哪个被填充上了)

total > bubbled[0] 比它大的才保留到bubbled
bubbled 保留最大的选项( 即填充上的选项 ) j
9.3 k = ANSWER_KEY[q] 是第几题(行)的正确答案
9.4 若k = bubbled[1],判断正确,correct+=1

.
10.打印正确率

# 10.打印正确率
score = (correct / 5.0) * 100
print("[INFO] score: {:.2f}%".format(score))
cv2.putText(warped, "{:.2f}%".format(score), (10, 30),
	cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
cv2.imshow("Original", image)
cv2.imshow("Exam", warped)
cv2.waitKey(0)
在这里插入图片描述

* 测试其他答题卡效果

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

结束语

虽然代码有点长,但大部分内容都是前面几个项目有用到的知识。可见遇到不同场景的举一反三能力多重要啦

扩展

有兴趣的同学们 可以尝试一下矩形答题卡的识别

完整代码

一个py文件,3个函数

# 导入工具包
import numpy as np
import argparse
import cv2
def order_points(pts):
	# 一共4个坐标点
	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

	# 计算输入的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))
    return cnts, boundingBoxes
def cv_show(name,img):
    cv2.imshow(name, img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()  

'''下面为主函数'''
if __name__ == "__main__":
	# 设置参数
	ap = argparse.ArgumentParser()
	ap.add_argument("-i", "--image", required=True,
		help="path to the input image")
	args = vars(ap.parse_args())

	# 正确答案
	ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}

	# 1.预处理
	image = cv2.imread(args["image"])
	contours_img = image.copy()
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	blurred = cv2.GaussianBlur(gray, (5, 5), 0)
	cv_show('blurred',blurred)
	edged = cv2.Canny(blurred, 75, 200)
	cv_show('edged',edged)

	# 2.轮廓检测
	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

	# 3.确保检测到了
	if len(cnts) > 0:
		# 根据轮廓大小进行排序
		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

	# 4.执行透视变换
	warped = four_point_transform(gray, docCnt.reshape(4, 2))
	cv_show('warped',warped)
	# 5.Otsu's 阈值处理
	thresh = cv2.threshold(warped, 0, 255,
		cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1] 
	cv_show('thresh',thresh)

	thresh_Contours = thresh.copy()
	# 6.找到所有轮廓
	cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
		cv2.CHAIN_APPROX_SIMPLE)[1]
	cv2.drawContours(thresh_Contours,cnts,-1,(0,0,255),3) 
	cv_show('thresh_Contours',thresh_Contours)
	questionCnts = []

	# 7.遍历所有圆圈轮廓(包括干扰项) 筛选出答题区域的圆
	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)

	# 8.按照从上到下进行排序
	questionCnts = sort_contours(questionCnts,
		method="top-to-bottom")[0]
	correct = 0

	# 9.每行的5个选项 分别比对正确答案
	for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):
		# 9.1排序
		cnts = sort_contours(questionCnts[i:i + 5])[0]
		bubbled = None

		# 9.2 遍历每一个结果
		for (j, c) in enumerate(cnts):
			# 9.2.1 使用mask来判断结果
			mask = np.zeros(thresh.shape, dtype="uint8")
			cv2.drawContours(mask, [c], -1, 255, -1) #-1表示填充
			# cv_show('mask',mask)
			# 9.2.2 通过计算非零点数量来算是否选择这个答案
			mask = cv2.bitwise_and(thresh, thresh, mask=mask)
			total = cv2.countNonZero(mask)

			# 9.2.3 通过阈值判断
			if bubbled is None or total > bubbled[0]:
				bubbled = (total, j)

		# 9.3 获取正确答案
		color = (0, 0, 255)
		k = ANSWER_KEY[q]

		# 9.4 对比答案 并 判断正确
		if k == bubbled[1]:
			color = (0, 255, 0)
			correct += 1

		# 9.5 绘图
		cv2.drawContours(warped, [cnts[k]], -1, color, 3)

	# 10.打印正确率
	score = (correct / 5.0) * 100
	print("[INFO] score: {:.2f}%".format(score))
	cv2.putText(warped, "{:.2f}%".format(score), (10, 30),
		cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)
	cv2.imshow("Original", image)
	cv2.imshow("Exam", warped)
	cv2.waitKey(0)
————————————————
版权声明:本文为CSDN博主「龙共日尧」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/sinat_29950703/article/details/108287249

相关文章收藏:

利用Python+opencv+TensorFlow框架打造 一个试卷批改系统

Python+OpenCV+PyQt开发答题卡识别软件源码

计算机视觉OpenCV答题卡识别项目实战

python爬取试题信息-保存文本并利用正则表达式获取指定字段并保存mysql数据库

原文链接:https://blog.csdn.net/weixin_44648900/article/details/105196981

疫情期间无聊突发奇想想要做一个在线考试系统,目前已完成数据库设计,开始编写爬虫爬取试题数据,目标网站如下,获取内容包括:考点,试题,答案选项,答案,解析。考点字段的获取便于以后系统个性化推荐的需要。🚔

在这里插入图片描述
在这里插入图片描述

去除网页里获取时候遇到的脏数据

查看网页的时候发现这个东西,可能是他们后台有其他用途,由于直接匹配字段不方便,先把所有网页文本先获取再把class为this_jammer等中内容获取为停用词表,爬取的试题文本去掉这些脏数据就OK了。

在这里插入图片描述

下面保存脏数据表的函数

在这里插入图片描述
#-*-coding:utf-8-*-
import requests
from bs4 import BeautifulSoup
# import codecs
def get_url(target_url, server, headers):
    req = requests.get(target_url, headers=headers)
    bf = BeautifulSoup(req.text)
    div = bf.find_all('div', class_='questions_col')
    a_bf = BeautifulSoup(str(div[0]))
    a = a_bf.find_all('a')
    cheak_parsing_url = []
    for each in a:
        if each.string == "查看解析":
            full_url = server + each.get('href')
            cheak_parsing_url.append(full_url)
    print(cheak_parsing_url)
    return cheak_parsing_url

def change_page(target_url, server, headers):
    req = requests.get(target_url, headers=headers)
    bf = BeautifulSoup(req.text)
    div = bf.find_all('div', class_='fenye')
    a_bf = BeautifulSoup(str(div[0]))
    a = a_bf.find_all('a')
    full_url = None
    for each in a:
        if each.string == "下一页":
            full_url = server + each.get('href')
            print(full_url)
        else :
            continue
    return full_url

def get_html(url_list, file_path, headers):
    for url in url_list:
        req = requests.get(url, headers=headers)
        content = req.content.decode('utf-8','ignore')
        bf = BeautifulSoup(content, fromEncoding="gb18030")
        del_text = bf.find_all(class_=["this_jammer", "hidejammersa", "jammerd42"])
        for i in del_text:
            if i:
                new_tag = ""
                try:
                    i.string.replace_with(new_tag)
                except:
                    pass
        texts = bf.find_all('div', class_= 'answer_detail')
        try:
            texts = texts[0].text.replace('\xa0', '')
            texts = texts.replace(" ", "")
        except:
            pass
        try:
            texts = texts.replace("\n", '')
        except:
            pass
        print(texts)
        contents_save(file_path, texts)

def contents_save(file_path, content):
    """
    :param file_path: 爬取文件保存路径
    :param content: 爬取文本文件内容
    :return: None
    """
    with open(file_path, 'a', encoding="utf-8", errors='ignore') as f:
        try:
            f.write(content)
        except:
            pass
        f.write('\n')

def get_category(target_url, server, headers):
    req = requests.get(target_url, headers=headers)
    bf = BeautifulSoup(req.text)
    div = bf.find_all('div', class_='shiti_catagory frame')
    a_bf = BeautifulSoup(str(div[0]))
    a = a_bf.find_all('a')
    category = []
    for each in a:
        full_url = server + each.get('href')
        category.append(full_url)
    print(category)
    return category

if __name__ == "__main__":
    main_url = "https://tiku.21cnjy.com/tiku.php?mod=quest&channel=8&xd=3"
    server = "https://tiku.21cnjy.com/"
    save_dir = "/Users/lidongliang/Desktop/爬虫/data"
    subject_file = "1.txt"
    file_path = save_dir + '/' + subject_file
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36',
        'Accept-Encoding': 'gzip'}
    categorys = get_category(main_url, server, headers)
    for category_url in categorys:
        counting = 0
        target_url = category_url
        while counting < 100:
            cheak_parsing_url = get_url(target_url, server, headers)
            get_html(cheak_parsing_url, file_path, headers)
            target_url = change_page(target_url, server, headers)

            if target_url == None:
                break
            counting += 1

运行初步结果如下:

在这里插入图片描述

对文本进行正则匹配获取文本指定字段并保存到数据库

import re
import pymysql

w1 = 'A.'
w2 = 'B.'
w3 = 'C.'
w4 = 'D.'
w5 = '答案'
w6 = '解析试题分析:'
w7 = '考点'


def get_txt():
    with open("/Users/lidongliang/Desktop/爬虫/data/1.txt", "r") as f:
        txt = f.readlines()
        return txt


def fen(txt):
    # buff = txt.replace('\n','')
    timu = re.compile('^' + '(.*?)' + w1, re.S).findall(txt)
    A = re.compile(w1 + '(.*?)' + w2, re.S).findall(txt)
    B = re.compile(w2 + '(.*?)' + w3, re.S).findall(txt)
    C = re.compile(w3 + '(.*?)' + w4, re.S).findall(txt)
    D = re.compile(w4 + '(.*?)' + w5, re.S).findall(txt)
    daan = re.compile(w5 + '(.*?)' + w6, re.S).findall(txt)
    jiexi = re.compile(w6 + '(.*?)' + w7, re.S).findall(txt)
    kaodian = re.compile(w7 + '(.*?)' + '\Z', re.S).findall(txt)

    timu.extend(A)
    timu.extend(B)
    timu.extend(C)
    timu.extend(D)
    timu.extend(daan)
    timu.extend(jiexi)
    timu.extend(kaodian)

    # print(timu)

    try:
        tg = timu[0]
        xx = ("A:" + timu[1] + "B:" + timu[2] + "C:" + timu[3] + "D:" + timu[4])
        da = timu[5]
        fx = timu[6]
        kd = timu[7]
    except:
        tg = '1'
        xx = '1'
        da = '1'
        fx = '1'
        kd = '1'
    con = pymysql.connect(host='localhost', user='root', passwd='00000000', db='login_test_1', charset='utf8')
    cursor = con.cursor()
    sql = "insert into question_info(tg,xx,da,fx,kd) values('%s','%s','%s','%s','%s')" \
          % (tg, xx, da, fx, kd)
    cursor.execute(sql)
    con.commit()


if __name__ == "__main__":
    txt = get_txt()
    for i in txt:
        fen(i)
    print("done")

最后结果:

在这里插入图片描述