首页
学习
活动
专区
圈层
工具
发布
社区首页 >专栏 >识别答题卡

识别答题卡

原创
作者头像
六合
发布于 2026-11-19 07:45:46
发布于 2026-11-19 07:45:46
200
举报

import cv2

import numpy as np

import pandas as pd

from typing import Dict, List, Tuple, Optional

class NewGaokaoAnswerSheetRecognizer:

def __init__(self):

# 新高考科目配置示例 (3+1+2模式)

self.subject_config = {

'common': ['chinese', 'math', 'english'], # 语数英(所有考生必考)

'preferred': ['physics', 'history'], # 首选科目(二选一)

'elective': { # 再选科目(四选二)

'physics_group': ['chemistry', 'biology', 'geography', 'politics'],

'history_group': ['chemistry', 'biology', 'geography', 'politics']

}

}

# 答题卡模板参数(需根据实际答题卡调整)

self.template_params = {

'定位点': {

'数量': 4,

'尺寸_mm': 8, # 8mm x 8mm

'位置': ['左上', '右上', '左下', '右下']

},

'考号区域': {

'行数': 9, # 9位考号

'列数': 10, # 0-9

'起始坐标': (100, 50) # 示例坐标

},

'科目识别码区域': {

'位置': (50, 150), # 用于识别物理组/历史组

'尺寸': (100, 30)

}

}

self.recognized_data = {

'student_id': '',

'subject_group': '',

'answers': {},

'raw_fill_values': {}

}

def preprocess_image(self, image_path: str, is_backside: bool = False) -> Tuple[np.ndarray, np.ndarray]:

"""

图像预处理:支持正反面的独立处理

Args:

image_path: 图像路径

is_backside: 是否是背面(有些答题卡背面有不同布局)

Returns:

original: 原始图像

binary: 预处理后的二值图像

"""

# 读取图像

img = cv2.imread(image_path)

if img is None:

raise FileNotFoundError(f"无法读取图像: {image_path}")

# 1. 灰度化 - 使用人眼感知加权公式 [citation:5]

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 2. 自适应阈值二值化 - 解决光照不均问题

# blockSize=15, C=2 是经过大量测试的黄金参数 [citation:5]

binary = cv2.adaptiveThreshold(

gray, 255,

cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

cv2.THRESH_BINARY_INV, # 填涂区域变白,便于分析

15, 2

)

# 3. 形态学操作 - 去除噪声,连接断裂线条

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))

binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel) # 闭运算补线

binary = cv2.medianBlur(binary, 3) # 中值滤波去椒盐噪声 [citation:5]

return img, binary

def locate_answer_sheet(self, binary_img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:

"""

定位答题卡并执行透视校正

Returns:

warped: 校正后的图像

transform_matrix: 透视变换矩阵

"""

# 1. 查找轮廓

contours, _ = cv2.findContours(

binary_img,

cv2.RETR_EXTERNAL,

cv2.CHAIN_APPROX_SIMPLE

)

# 2. 筛选最大的四边形(应该是答题卡轮廓)

max_area = 0

sheet_contour = None

for contour in contours:

area = cv2.contourArea(contour)

if area < 10000: # 过滤太小的轮廓

continue

# 多边形近似

epsilon = 0.02 * cv2.arcLength(contour, True)

approx = cv2.approxPolyDP(contour, epsilon, True)

# 如果是四边形且面积最大

if len(approx) == 4 and area > max_area:

max_area = area

sheet_contour = approx

if sheet_contour is None:

raise ValueError("未找到答题卡轮廓")

# 3. 获取四个角点并排序 (左上、右上、右下、左下)

pts = sheet_contour.reshape(4, 2)

rect = np.zeros((4, 2), dtype=np.float32)

# 计算中心点

center = np.mean(pts, axis=0)

# 根据角度排序

angles = []

for pt in pts:

angle = np.arctan2(pt[1] - center[1], pt[0] - center[0])

angles.append(angle)

sorted_idx = np.argsort(angles)

pts = pts[sorted_idx]

# 调整顺序为:左上、右上、右下、左下

rect[0] = pts[0] # 左上

rect[1] = pts[1] # 右上

rect[2] = pts[2] # 右下

rect[3] = pts[3] # 左下

# 4. 计算目标尺寸

width = max(

np.linalg.norm(rect[1] - rect[0]),

np.linalg.norm(rect[2] - rect[3])

)

height = max(

np.linalg.norm(rect[3] - rect[0]),

np.linalg.norm(rect[2] - rect[1])

)

# 5. 执行透视变换 [citation:5]

dst_pts = np.array([

[0, 0],

[width - 1, 0],

[width - 1, height - 1],

[0, height - 1]

], dtype=np.float32)

transform_matrix = cv2.getPerspectiveTransform(rect, dst_pts)

warped = cv2.warpPerspective(

binary_img, transform_matrix,

(int(width), int(height))

)

return warped, transform_matrix

def locate_registration_marks(self, binary_img: np.ndarray) -> Dict[str, Tuple[int, int]]:

"""

定位答题卡四角的定位标记(黑块)

这些标记用于精确校正和区域划分 [citation:5]

"""

# 使用模板匹配查找定位点

marks = {}

# 创建定位点模板(8x8mm的黑色方块)

template_size = 30 # 像素,需根据实际DPI调整

template = np.zeros((template_size, template_size), dtype=np.uint8)

cv2.rectangle(template, (2, 2), (template_size-2, template_size-2), 255, -1)

# 在图像四角区域搜索

h, w = binary_img.shape

search_regions = {

'top_left': (0, 0, w//4, h//4),

'top_right': (w*3//4, 0, w//4, h//4),

'bottom_left': (0, h*3//4, w//4, h//4),

'bottom_right': (w*3//4, h*3//4, w//4, h//4)

}

for name, (x, y, rw, rh) in search_regions.items():

roi = binary_img[y:y+rh, x:x+rw]

if roi.size == 0:

continue

# 模板匹配

result = cv2.matchTemplate(roi, template, cv2.TM_CCOEFF_NORMED)

_, max_val, _, max_loc = cv2.minMaxLoc(result)

if max_val > 0.6: # 匹配度阈值

marks[name] = (x + max_loc[0] + template_size//2,

y + max_loc[1] + template_size//2)

return marks

def extract_student_id(self, binary_img: np.ndarray) -> str:

"""

识别学生考号(9位数字填涂)

使用行列投影法识别填涂 [citation:6]

"""

h, w = binary_img.shape

# 考号区域坐标(需根据实际答题卡标定)

id_x_start, id_y_start = 200, 100

id_width, id_height = 400, 300

id_region = binary_img[id_y_start:id_y_start+id_height,

id_x_start:id_x_start+id_width]

# 划分9行(数字位)和10列(0-9选项)

digit_height = id_height // 9

digit_width = id_width // 10

student_id = ''

fill_threshold = 0.64 # 填涂面积阈值(64%面积被涂黑算填涂)[citation:6]

for row in range(9): # 9位考号

max_fill_ratio = 0

selected_digit = None

for col in range(10): # 每个数字位的10个选项

# 提取单个选项区域

x = col * digit_width

y = row * digit_height

option_region = id_region[y:y+digit_height, x:x+digit_width]

# 计算填涂比例

fill_ratio = np.sum(option_region == 255) / option_region.size

if fill_ratio > max_fill_ratio:

max_fill_ratio = fill_ratio

selected_digit = col

# 判断是否有效填涂

if max_fill_ratio >= fill_threshold:

student_id += str(selected_digit)

else:

student_id += '?' # 未填涂或模糊

return student_id

def detect_subject_group(self, binary_img: np.ndarray) -> str:

"""

识别考生选择的科目组(物理组/历史组)

通过科目识别码区域判断 [citation:8]

"""

# 科目识别码区域(通常是一个特殊标记或填涂区)

x, y = self.template_params['科目识别码区域']['位置']

w, h = self.template_params['科目识别码区域']['尺寸']

code_region = binary_img[y:y+h, x:x+w]

# 简单的二值化判断

mean_value = np.mean(code_region)

# 根据识别码判断科目组(实际应用中需要更复杂的逻辑)

if mean_value > 127:

return 'physics_group' # 物理组

else:

return 'history_group' # 历史组

def extract_answers(self, binary_img: np.ndarray, subject_group: str) -> Dict[str, List[str]]:

"""

提取所有题目的填涂答案

支持多科目合卡,根据科目组选择需要识别的区域 [citation:7]

"""

answers = {}

# 根据科目组确定要识别的科目

subjects = ['chinese', 'math', 'english'] # 语数英必考

if subject_group == 'physics_group':

subjects.append('physics') # 首选科目

# 再选科目(4选2)- 需要特殊处理,通常会有4个填涂区选2个

subjects.extend(['elective1', 'elective2'])

else: # history_group

subjects.append('history')

subjects.extend(['elective1', 'elective2'])

# 各科目答题区域坐标(需根据实际答题卡标定)

# 这里使用示例坐标,实际应用中需要通过模板文件配置

subject_regions = {

'chinese': {'x': 50, 'y': 200, 'w': 500, 'h': 400, 'questions': 15, 'options': 4},

'math': {'x': 50, 'y': 650, 'w': 500, 'h': 400, 'questions': 12, 'options': 4},

'english': {'x': 600, 'y': 200, 'w': 500, 'h': 400, 'questions': 15, 'options': 4},

'physics': {'x': 600, 'y': 650, 'w': 500, 'h': 400, 'questions': 10, 'options': 4},

'history': {'x': 600, 'y': 650, 'w': 500, 'h': 400, 'questions': 10, 'options': 4},

'elective1': {'x': 50, 'y': 1100, 'w': 500, 'h': 200, 'questions': 5, 'options': 4},

'elective2': {'x': 600, 'y': 1100, 'w': 500, 'h': 200, 'questions': 5, 'options': 4}

}

# 对每个科目提取答案

for subject in subjects:

if subject not in subject_regions:

continue

region = subject_regions[subject]

roi = binary_img[region['y']:region['y']+region['h'],

region['x']:region['x']+region['w']]

# 计算每个题目的每个选项区域

q_height = region['h'] // region['questions']

opt_width = region['w'] // region['options']

subject_answers = []

for q in range(region['questions']):

filled_options = []

for opt in range(region['options']):

# 提取选项区域

x = opt * opt_width

y = q * q_height

opt_region = roi[y:y+q_height, x:x+opt_width]

# 计算填涂比例

fill_ratio = np.sum(opt_region == 255) / opt_region.size

# 填涂判断阈值,可根据实际情况调整 [citation:6]

if fill_ratio > 0.4:

filled_options.append(chr(65 + opt)) # A, B, C, D...

subject_answers.append(''.join(filled_options) if filled_options else '')

answers[subject] = subject_answers

return answers

def calculate_score(self, answers: Dict[str, List[str]],

answer_key: Dict[str, List[str]]) -> Dict[str, float]:

"""

计算得分(支持赋分制)

Args:

answers: 识别出的学生答案

answer_key: 标准答案

Returns:

各科目得分和原始总分

"""

scores = {}

total_raw_score = 0

for subject, student_ans in answers.items():

if subject not in answer_key:

continue

key = answer_key[subject]

subject_score = 0

# 逐题比对

for i, (s_ans, k_ans) in enumerate(zip(student_ans, key)):

if s_ans and s_ans == k_ans: # 单选情况

# 假设每题3分

subject_score += 3

elif s_ans and set(s_ans) == set(k_ans): # 多选全对

subject_score += 3

# 可根据实际规则增加部分得分逻辑

scores[subject] = subject_score

total_raw_score += subject_score

scores['raw_total'] = total_raw_score

# 如果是再选科目,需要进行赋分转换(示例逻辑)

if 'elective1' in scores:

# 根据原始分在全省(或本校)的排名进行赋分

# 这里简化处理:原始分 -> 等级赋分(100分制)

scores['elective1_converted'] = self.raw_to_rank_score(scores['elective1'], 3, 5)

scores['elective2_converted'] = self.raw_to_rank_score(scores['elective2'], 3, 5)

return scores

def raw_to_rank_score(self, raw_score: float, question_count: int,

score_per_question: int) -> int:

"""

原始分转等级赋分(模拟)

新高考再选科目采用等级赋分制 [citation:3][citation:8]

"""

# 这是一个简化的示例,实际需要根据全省排名

max_possible = question_count * score_per_question

percentage = raw_score / max_possible if max_possible > 0 else 0

# 假设的赋分转换表

if percentage >= 0.9:

return 100

elif percentage >= 0.8:

return 90

elif percentage >= 0.7:

return 80

elif percentage >= 0.6:

return 70

elif percentage >= 0.5:

return 60

else:

return 50

def process_answer_sheet(self, front_image: str, back_image: Optional[str] = None,

answer_key: Optional[Dict[str, List[str]]] = None) -> Dict:

"""

主处理流程:支持正反面答题卡 [citation:3][citation:8]

"""

print("=" * 60)

print("新高考答题卡识别系统启动")

print("=" * 60)

result = {

'student_id': '',

'subject_group': '',

'answers': {},

'scores': {},

'images': {},

'status': 'success'

}

try:

# 1. 处理正面

print("\n1. 处理答题卡正面...")

img_front, binary_front = self.preprocess_image(front_image, is_backside=False)

# 2. 定位并校正

print("2. 图像定位与校正...")

warped_front, _ = self.locate_answer_sheet(binary_front)

# 3. 识别考号

print("3. 识别考生考号...")

student_id = self.extract_student_id(warped_front)

result['student_id'] = student_id

print(f" 考号: {student_id}")

# 4. 识别科目组

print("4. 识别科目组...")

subject_group = self.detect_subject_group(warped_front)

result['subject_group'] = subject_group

print(f" 科目组: {subject_group}")

# 5. 提取答案

print("5. 提取填涂答案...")

answers = self.extract_answers(warped_front, subject_group)

result['answers'] = answers

# 如果有背面,继续处理

if back_image:

print("\n6. 处理答题卡背面...")

img_back, binary_back = self.preprocess_image(back_image, is_backside=True)

warped_back, _ = self.locate_answer_sheet(binary_back)

back_answers = self.extract_answers(warped_back, subject_group)

# 合并正反面答案

for subject, ans in back_answers.items():

if subject not in answers:

answers[subject] = ans

# 6. 计算得分

if answer_key:

print("\n7. 计算得分...")

scores = self.calculate_score(answers, answer_key)

result['scores'] = scores

print(f" 原始总分: {scores.get('raw_total', 0)}")

if 'elective1_converted' in scores:

print(f" 再选科目1赋分: {scores['elective1_converted']}")

print(f" 再选科目2赋分: {scores['elective2_converted']}")

# 保存中间图像用于调试

result['images']['front_corrected'] = warped_front

print("\n" + "=" * 60)

print("识别完成!")

print("=" * 60)

except Exception as e:

result['status'] = 'error'

result['error_message'] = str(e)

print(f"\n处理出错: {e}")

return result

def export_to_excel(self, result: Dict, output_path: str):

"""导出识别结果到Excel"""

# 构建DataFrame

data = {

'考号': [result['student_id']],

'科目组': [result['subject_group']],

'识别状态': [result['status']]

}

# 添加各科目答案

for subject, answers in result.get('answers', {}).items():

data[f'{subject}_答案'] = [' '.join(answers)]

# 添加得分

for subject, score in result.get('scores', {}).items():

data[f'{subject}_得分'] = [score]

df = pd.DataFrame(data)

df.to_excel(output_path, index=False)

print(f"\n结果已导出到: {output_path}")

# ==================== 使用示例 ====================

if __name__ == "__main__":

# 初始化识别器

recognizer = NewGaokaoAnswerSheetRecognizer()

# 标准答案示例(新高考物理组)

answer_key = {

'chinese': ['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C'],

'math': ['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D'],

'english': ['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B', 'C'],

'physics': ['A', 'B', 'C', 'D', 'A', 'B', 'C', 'D', 'A', 'B'],

'elective1': ['A', 'B', 'C', 'D', 'A'],

'elective2': ['B', 'C', 'D', 'A', 'B']

}

# 处理答题卡(假设有正反面)

result = recognizer.process_answer_sheet(

front_image='gaokao_answer_sheet_front.jpg',

back_image='gaokao_answer_sheet_back.jpg', # 可选

answer_key=answer_key

)

# 导出结果

if result['status'] == 'success':

recognizer.export_to_excel(result, 'recognition_result.xlsx')

原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。

如有侵权,请联系 cloudcommunity@tencent.com 删除。

问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档