基于计算机视觉的试卷答题区表格识别与提取技术

[复制链接]
发表于 2025-9-12 08:00:20 | 显示全部楼层 |阅读模式
基于计算机视觉的试卷答题区表格识别与提取技术

摘要

本文先容了一种基于计算机视觉技术的试卷答题区表格识别与提取算法。该算法能够自动从试卷图像中定位答题区表格,执行图像方向矫正,准确识别表格网格线,并提取每个答案单位格。本技术可广泛应用于教育测评、测验管理系统等场景,极大提高答卷处置惩罚效率。
关键技术


  • 表格地区提取与分割
  • 图像二值化预处置惩罚
  • 多标准形态学利用
  • 水平线与竖线准确检测
  • 单位格定位与提取
1. 系统架构

我们设计的试卷答题区表格处置惩罚工具由以下重要模块组成:

  • 答题区定位:从整张试卷图像中提取右上角的答题区表格
  • 图像预处置惩罚:举行二值化、去噪等利用以增强表格线条
  • 表格网格识别:准确检测水平线和竖线位置
  • 单位格提取:根据网格线交点切割并生存各个答案单位格
处置惩罚流程:
  1. 输入图像 -> 答题区定位 -> 方向矫正 -> 图像预处理 ->
  2. 网格线检测 -> 单元格提取 -> 输出结果
复制代码
2. 焦点功能实现

2.1 答题区表格定位

我们假设答题区通常位于试卷右上角,起首提取该地区并应用表面检测算法:
  1. # 提取右上角区域(答题区域通常在试卷右上角)
  2. x_start = int(width * 0.6)
  3. y_start = 0
  4. w = width - x_start
  5. h = int(height * 0.5)
  6. # 提取区域
  7. region = img[y_start:y_start + h, x_start:x_start + w]
复制代码
接着使用形态学利用提取线条并查找表格表面:
  1. # 转为灰度图并二值化
  2. gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
  3. binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
  4.                                cv2.THRESH_BINARY_INV, 11, 2)
  5. # 使用形态学操作检测线条
  6. horizontal_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_h, iterations=2)
  7. vertical_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_v, iterations=2)
复制代码
2.2 图像预处置惩罚

为了增强表格线条特性,我们执行以下预处置惩罚步调:
  1. # 高斯平滑去噪
  2. blurred = cv2.GaussianBlur(gray, (5, 5), 0)
  3. # 自适应阈值二值化
  4. binary = cv2.adaptiveThreshold(
  5.     blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 21, 5)
  6. # 形态学操作填充小空隙
  7. kernel = np.ones((3, 3), np.uint8)
  8. binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
复制代码
2.3 表格网格线识别

这是本算法的焦点部门,我们分别检测水平线和竖线:
2.3.1 水平线检测

使用形态学开运算提取水平线,然后计算投影找到线条位置:
  1. horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal_size, 1))
  2. horizontal_lines = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
  3. # 提取水平线坐标 - 基于行投影
  4. h_coords = []
  5. h_projection = np.sum(horizontal_lines, axis=1)
  6. for i in range(1, len(h_projection) - 1):
  7.     if h_projection[i] > h_projection[i - 1] and h_projection[i] > h_projection[i + 1] and h_projection[i] > width // 5:
  8.         h_coords.append(i)
复制代码
2.3.2 竖线检测

竖线检测采用多标准计谋,使用不同大小的结构元素,提高检测的鲁棒性:
  1. # 使用不同大小的结构元素进行竖线检测
  2. vertical_kernels = [
  3.     cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 12)),  # 细线
  4.     cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 8)),  # 中等
  5.     cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 4))  # 粗线
  6. ]
  7. # 合并不同尺度的检测结果
  8. vertical_lines = np.zeros_like(binary_image)
  9. for kernel in vertical_kernels:
  10.     v_lines = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel, iterations=1)
  11.     vertical_lines = cv2.bitwise_or(vertical_lines, v_lines)
复制代码
2.4 表格竖线位置准确校正

由于竖线检测大概存在偏左问题,我们实现了复杂的位置校正算法:
  1. # 竖线位置修正:解决偏左问题 - 检测实际线条中心位置
  2. v_coords_corrected = []
  3. for idx, v_coord in enumerate(v_coords_detected):
  4.     # 第2-11根竖线特殊处理
  5.     if 1 <= idx <= 10:  # 第2-11根竖线
  6.         search_range_left = 2  # 左侧搜索范围更小
  7.         search_range_right = 12  # 右侧搜索范围大幅增大
  8.     else:
  9.         search_range_left = 5
  10.         search_range_right = 5
  11.    
  12.     # 在搜索范围内找到峰值中心位置
  13.     # 对于特定竖线,使用加权平均来偏向右侧
  14.     if 1 <= idx <= 10:
  15.         window = col_sum[left_bound:right_bound+1]
  16.         weights = np.linspace(0.3, 2.0, len(window))  # 更强的右侧权重
  17.         weighted_window = window * weights
  18.         max_pos = left_bound + np.argmax(weighted_window)
  19.         # 强制向右偏移
  20.         max_pos += 3
  21.     else:
  22.         max_pos = left_bound + np.argmax(col_sum[left_bound:right_bound+1])
复制代码
2.4.1 不等间距网格处置惩罚

我们根据实际表格特点,处置惩罚了第一列宽度与其他列不同的环境:
  1. # 设置第一列的宽度为其他列的1.3倍
  2. first_column_width_ratio = 1.3
  3. # 计算除第一列外每列的宽度
  4. remaining_width = right_bound - left_bound
  5. regular_column_width = remaining_width / (expected_vlines - 1 + (first_column_width_ratio - 1))
复制代码
2.5 单位格提取与生存

根据检测到的网格线,我们提取出每个单位格:
  1. # 提取单元格的过程
  2. cell_img = image[y1_m:y2_m, x1_m:x2_m].copy()
  3. # 保存单元格图片
  4. cell_filename = f'cell_0{q_num:02d}.png'
  5. cell_path = os.path.join(output_dir, cell_filename)
  6. cv2.imwrite(cell_path, cell_img)
复制代码
3. 技术创新点


  • 多标准形态学利用:使用不同尺寸的结构元素检测竖线,提高了检测的鲁棒性
  • 表格线位置动态校正:针对不同位置的竖线采用不同的校正计谋,解决了竖线偏左问题
  • 不等间距网格处置惩罚:通过特殊计算处置惩罚第一列宽度不同的环境,更好地适应实际试卷样式
  • 加权峰值搜索:使用加权计谋举行峰值搜索,提高了线条中心位置的准确性
4. 使用示例

4.1 根本用法
  1. from image_processing import process_image
  2. # 处理单张图像
  3. input_image = "./images/1.jpg"
  4. output_dir = "./output"
  5. image_paths = process_image(input_image, output_dir)
  6. print(f"处理成功: 共生成{len(image_paths)}个单元格图片")
复制代码
4.2 批量处置惩罚

我们还提供了批量处置惩罚多张试卷图像的功能
  1. # 批量处理目录中的所有图像
  2. for img_file in image_files:
  3.     img_path = os.path.join(images_dir, img_file)
  4.     output_dir = os.path.join(output_base_dir, f"result_{img_name}")
  5.     image_paths = process_image(img_path, output_dir)
复制代码
4.3 完整代码
  1. """
  2. 试卷答题区表格处理工具
  3. 1. 从试卷提取答题区表格
  4. 2. 对表格进行方向矫正
  5. 3. 切割表格单元格并保存所有25道题的答案单元格
  6. """
  7. import os
  8. import cv2
  9. import numpy as np
  10. import argparse
  11. import sys
  12. import time
  13. import shutil
  14. class AnswerSheetProcessor:
  15.     """试卷答题区表格处理工具类"""
  16.     def __init__(self):
  17.         """初始化处理器"""
  18.         pass
  19.     def process(self, input_image_path, output_dir):
  20.         """
  21.         处理试卷答题区,提取表格并保存单元格
  22.         Args:
  23.             input_image_path: 输入图像路径
  24.             output_dir: 输出单元格图像的目录
  25.         Returns:
  26.             处理后的图片路径列表,失败时返回空列表
  27.         """
  28.         os.makedirs(output_dir, exist_ok=True)
  29.         temp_dir = os.path.join(os.path.dirname(output_dir), f"temp_{time.strftime('%Y%m%d_%H%M%S')}")
  30.         os.makedirs(temp_dir, exist_ok=True)
  31.         try:
  32.             # 1. 提取答题区表格
  33.             table_img, _ = self._extract_answer_table(input_image_path, temp_dir)
  34.             if table_img is None:
  35.                 print("无法提取答题区表格")
  36.                 return []
  37.             # 保存提取的原始表格图像
  38.             # original_table_path = os.path.join(output_dir, "original_table.png")
  39.             # cv2.imwrite(original_table_path, table_img)
  40.             # 2. 矫正表格方向
  41.             corrected_table = self._correct_table_orientation(table_img)
  42.             # cv2.imwrite(os.path.join(output_dir, "corrected_table.png"), corrected_table)
  43.             # 3. 提取表格单元格
  44.             image_paths = self._process_and_save_cells(corrected_table, temp_dir, output_dir)
  45.             # 4. 清理临时目录
  46.             shutil.rmtree(temp_dir, ignore_errors=True)
  47.             return image_paths
  48.         except Exception as e:
  49.             print(f"处理失败: {str(e)}")
  50.             shutil.rmtree(temp_dir, ignore_errors=True)
  51.             return []
  52.     def _extract_answer_table(self, image, output_dir):
  53.         """提取试卷答题区表格"""
  54.         # 读取图像
  55.         if isinstance(image, str):
  56.             img = cv2.imread(image)
  57.             if img is None:
  58.                 return None, None
  59.         else:
  60.             img = image
  61.         # 调整图像大小以提高处理速度
  62.         max_width = 1500
  63.         if img.shape[1] > max_width:
  64.             scale = max_width / img.shape[1]
  65.             img = cv2.resize(img, None, fx=scale, fy=scale)
  66.         # 获取图像尺寸
  67.         height, width = img.shape[:2]
  68.         # 提取右上角区域(答题区域通常在试卷右上角)
  69.         x_start = int(width * 0.6)
  70.         y_start = 0
  71.         w = width - x_start
  72.         h = int(height * 0.5)
  73.         # 提取区域
  74.         region = img[y_start:y_start + h, x_start:x_start + w]
  75.         # 转为灰度图并二值化
  76.         gray = cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)
  77.         binary = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
  78.                                        cv2.THRESH_BINARY_INV, 11, 2)
  79.         # 检测表格线
  80.         kernel_h = cv2.getStructuringElement(cv2.MORPH_RECT, (max(25, w // 20), 1))
  81.         kernel_v = cv2.getStructuringElement(cv2.MORPH_RECT, (1, max(25, h // 20)))
  82.         horizontal_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_h, iterations=2)
  83.         vertical_lines = cv2.morphologyEx(binary, cv2.MORPH_OPEN, kernel_v, iterations=2)
  84.         # 合并线条
  85.         grid_lines = cv2.add(horizontal_lines, vertical_lines)
  86.         # 膨胀线条
  87.         kernel = np.ones((3, 3), np.uint8)
  88.         dilated_lines = cv2.dilate(grid_lines, kernel, iterations=1)
  89.         # 查找轮廓
  90.         contours, _ = cv2.findContours(dilated_lines, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  91.         # 筛选可能的表格轮廓
  92.         valid_contours = []
  93.         for contour in contours:
  94.             x, y, w, h = cv2.boundingRect(contour)
  95.             area = cv2.contourArea(contour)
  96.             if area < 1000:
  97.                 continue
  98.             aspect_ratio = float(w) / h if h > 0 else 0
  99.             if 0.1 <= aspect_ratio <= 3.0:
  100.                 valid_contours.append((x, y, w, h, area))
  101.         if valid_contours:
  102.             # 选择面积最大的轮廓
  103.             valid_contours.sort(key=lambda c: c[4], reverse=True)
  104.             x, y, w, h, _ = valid_contours[0]
  105.             # 调整回原图坐标
  106.             x_abs = x_start + x
  107.             y_abs = y_start + y
  108.             # 提取表格区域并加一些padding确保完整
  109.             padding = 10
  110.             x_abs = max(0, x_abs - padding)
  111.             y_abs = max(0, y_abs - padding)
  112.             w_padded = min(width - x_abs, w + 2 * padding)
  113.             h_padded = min(height - y_abs, h + 2 * padding)
  114.             table_region = img[y_abs:y_abs + h_padded, x_abs:x_abs + w_padded]
  115.             return table_region, (x_abs, y_abs, w_padded, h_padded)
  116.         # 如果未找到有效轮廓,返回预估区域
  117.         x_start = int(width * 0.75)
  118.         y_start = int(height * 0.15)
  119.         w = int(width * 0.2)
  120.         h = int(height * 0.4)
  121.         x_start = max(0, min(x_start, width - 1))
  122.         y_start = max(0, min(y_start, height - 1))
  123.         w = min(width - x_start, w)
  124.         h = min(height - y_start, h)
  125.         return img[y_start:y_start + h, x_start:x_start + w], (x_start, y_start, w, h)
  126.     def _correct_table_orientation(self, table_img):
  127.         """矫正表格方向(逆时针旋转90度)"""
  128.         if table_img is None:
  129.             return None
  130.         try:
  131.             return cv2.rotate(table_img, cv2.ROTATE_90_COUNTERCLOCKWISE)
  132.         except Exception as e:
  133.             print(f"表格方向矫正失败: {str(e)}")
  134.             return table_img
  135.     def _process_and_save_cells(self, table_img, temp_dir, output_dir):
  136.         """处理表格并保存单元格"""
  137.         try:
  138.             # 预处理图像
  139.             binary = self._preprocess_image(table_img)
  140.             # cv2.imwrite(os.path.join(output_dir, "binary_table.png"), binary)
  141.             # 检测表格网格
  142.             h_lines, v_lines = self._detect_table_cells(binary, table_img.shape, output_dir)
  143.             # 如果未检测到足够的网格线
  144.             if len(h_lines) < 2 or len(v_lines) < 2:
  145.                 print("未检测到足够的表格线")
  146.                 return []
  147.             # 可视化并保存表格网格
  148.             self._visualize_grid(table_img, h_lines, v_lines, output_dir)
  149.             # 提取并直接保存单元格
  150.             image_paths = self._extract_and_save_cells(table_img, h_lines, v_lines, output_dir)
  151.             return image_paths
  152.         except Exception as e:
  153.             print(f"表格处理错误: {str(e)}")
  154.             return []
  155.     def _preprocess_image(self, image):
  156.         """表格图像预处理"""
  157.         if image is None:
  158.             return None
  159.         # 转为灰度图
  160.         if len(image.shape) == 3:
  161.             gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  162.         else:
  163.             gray = image.copy()
  164.         # 高斯平滑
  165.         blurred = cv2.GaussianBlur(gray, (5, 5), 0)
  166.         # 自适应阈值二值化
  167.         binary = cv2.adaptiveThreshold(
  168.             blurred, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 21, 5)
  169.         # 进行形态学操作,填充小空隙
  170.         kernel = np.ones((3, 3), np.uint8)
  171.         binary = cv2.morphologyEx(binary, cv2.MORPH_CLOSE, kernel)
  172.         return binary
  173.     def _detect_table_cells(self, binary_image, image_shape, output_dir):
  174.         """检测表格网格,基于图像真实表格线精确定位"""
  175.         height, width = image_shape[:2]
  176.         # 1. 先检测水平线
  177.         horizontal_size = width // 10
  178.         horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontal_size, 1))
  179.         horizontal_lines = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, horizontal_kernel, iterations=2)
  180.         
  181.         # 提取水平线坐标
  182.         h_coords = []
  183.         h_projection = np.sum(horizontal_lines, axis=1)
  184.         for i in range(1, len(h_projection) - 1):
  185.             if h_projection[i] > h_projection[i - 1] and h_projection[i] > h_projection[i + 1] and h_projection[
  186.                 i] > width // 5:
  187.                 h_coords.append(i)
  188.         # 使用聚类合并相近的水平线
  189.         h_coords = self._cluster_coordinates(h_coords, eps=height // 30)
  190.         # 2. 确保我们至少有足够的水平线定义表格区域
  191.         if len(h_coords) < 2:
  192.             print("警告: 水平线检测不足,无法确定表格范围")
  193.             h_lines = [(0, int(y), width, int(y)) for y in h_coords]
  194.             v_lines = []
  195.             return h_lines, v_lines
  196.         # 获取表格垂直范围
  197.         h_coords.sort()
  198.         table_top = int(h_coords[0])
  199.         table_bottom = int(h_coords[-1])
  200.         # 3. 增强竖线检测 - 使用多尺度检测策略
  201.         # 使用不同大小的结构元素进行竖线检测
  202.         vertical_kernels = [
  203.             cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 12)),  # 细线
  204.             cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 8)),  # 中等
  205.             cv2.getStructuringElement(cv2.MORPH_RECT, (1, (table_bottom - table_top) // 4))  # 粗线
  206.         ]
  207.         # 合并不同尺度的检测结果
  208.         vertical_lines = np.zeros_like(binary_image)
  209.         for kernel in vertical_kernels:
  210.             v_lines = cv2.morphologyEx(binary_image, cv2.MORPH_OPEN, kernel, iterations=1)
  211.             vertical_lines = cv2.bitwise_or(vertical_lines, v_lines)
  212.         # 只关注表格区域内的竖线
  213.         table_region_v = vertical_lines[table_top:table_bottom, :]
  214.         # 计算列投影
  215.         col_sum = np.sum(table_region_v, axis=0)
  216.         # 4. 更精准地寻找竖线位置
  217.         # 使用自适应阈值计算
  218.         local_max_width = width // 25  # 更精细的局部最大值搜索窗口
  219.         threshold_ratio = 0.15  # 降低阈值以捕获更多可能的竖线
  220.         # 自适应阈值计算
  221.         threshold = np.max(col_sum) * threshold_ratio
  222.         # 扫描所有列查找峰值
  223.         v_coords_raw = []
  224.         i = 0
  225.         while i < len(col_sum):
  226.             # 查找局部范围内的峰值
  227.             local_end = min(i + local_max_width, len(col_sum))
  228.             local_peak = i
  229.             # 找到局部最大值
  230.             for j in range(i, local_end):
  231.                 if col_sum[j] > col_sum[local_peak]:
  232.                     local_peak = j
  233.             # 如果局部最大值大于阈值,认为是竖线
  234.             if col_sum[local_peak] > threshold:
  235.                 v_coords_raw.append(local_peak)
  236.                 # 跳过已处理的区域
  237.                 i = local_peak + local_max_width // 2
  238.             else:
  239.                 i += 1
  240.         # 5. 去除过于接近的竖线(可能是同一条线被重复检测)
  241.         v_coords_detected = self._cluster_coordinates(v_coords_raw, eps=width // 50)  # 使用更小的合并阈值
  242.         # 6. 检查找到的竖线数量
  243.         expected_vlines = 15  # 预期应有15条竖线
  244.         print(f"初步检测到竖线数量: {len(v_coords_detected)}")
  245.         # 7. 处理识别结果
  246.         if len(v_coords_detected) > 0:
  247.             # 7.1 获取表格的左右边界
  248.             v_coords_detected.sort()  # 确保按位置排序
  249.             
  250.             # 竖线位置修正:解决偏左问题 - 检测实际线条中心位置
  251.             v_coords_corrected = []
  252.             for idx, v_coord in enumerate(v_coords_detected):
  253.                 # 在竖线坐标附近寻找准确的线条中心
  254.                 # 对于第2-11根竖线,使用更大的搜索范围向右偏移
  255.                 if 1 <= idx <= 10:  # 第2-11根竖线
  256.                     search_range_left = 2  # 左侧搜索范围更小
  257.                     search_range_right = 12  # 右侧搜索范围大幅增大
  258.                 else:
  259.                     search_range_left = 5
  260.                     search_range_right = 5
  261.                
  262.                 left_bound = max(0, v_coord - search_range_left)
  263.                 right_bound = min(width - 1, v_coord + search_range_right)
  264.                
  265.                 if left_bound < right_bound and left_bound < len(col_sum) and right_bound < len(col_sum):
  266.                     # 在搜索范围内找到峰值中心位置
  267.                     # 对于第2-11根竖线,使用加权平均来偏向右侧
  268.                     if 1 <= idx <= 10:
  269.                         # 计算加权平均,右侧权重更大
  270.                         window = col_sum[left_bound:right_bound+1]
  271.                         weights = np.linspace(0.3, 2.0, len(window))  # 更强的右侧权重
  272.                         weighted_window = window * weights
  273.                         max_pos = left_bound + np.argmax(weighted_window)
  274.                         # 强制向右偏移2-3像素
  275.                         max_pos += 3
  276.                         max_pos = min(right_bound, max_pos)
  277.                     else:
  278.                         max_pos = left_bound + np.argmax(col_sum[left_bound:right_bound+1])
  279.                     
  280.                     v_coords_corrected.append(max_pos)
  281.                 else:
  282.                     v_coords_corrected.append(v_coord)
  283.             
  284.             # 使用修正后的坐标
  285.             v_coords_detected = v_coords_corrected
  286.             
  287.             left_bound = v_coords_detected[0]  # 最左边的竖线
  288.             right_bound = v_coords_detected[-1]  # 最右边的竖线
  289.             # 7.2 计算理想的等距离竖线位置,但使第一列宽度比其他列宽
  290.             ideal_vlines = []
  291.             
  292.             # 设置第一列的宽度为其他列的1.5倍
  293.             first_column_width_ratio = 1.3
  294.             
  295.             # 计算除第一列外每列的宽度
  296.             remaining_width = right_bound - left_bound
  297.             regular_column_width = remaining_width / (expected_vlines - 1 + (first_column_width_ratio - 1))
  298.             
  299.             # 设置第一列
  300.             ideal_vlines.append(int(left_bound))
  301.             
  302.             # 设置第二列位置
  303.             ideal_vlines.append(int(left_bound + regular_column_width * first_column_width_ratio))
  304.             
  305.             # 设置剩余列
  306.             for i in range(2, expected_vlines):
  307.                 ideal_vlines.append(int(left_bound + regular_column_width * (i + (first_column_width_ratio - 1))))
  308.             # 7.3 使用修正后的列位置
  309.             v_coords = ideal_vlines
  310.             
  311.             # 进一步向右偏移第2-11根竖线(总共15根)
  312.             for i in range(1, 11):
  313.                 if i < len(v_coords):
  314.                     v_coords[i] += 3  # 向右偏移3像素
  315.         else:
  316.             # 如果没有检测到竖线,使用预估等距离
  317.             print("未检测到任何竖线,使用预估等距离")
  318.             left_bound = width // 10
  319.             right_bound = width * 9 // 10
  320.             # 计算除第一列外每列的宽度
  321.             first_column_width_ratio = 1.5
  322.             remaining_width = right_bound - left_bound
  323.             regular_column_width = remaining_width / (expected_vlines - 1 + (first_column_width_ratio - 1))
  324.             
  325.             # 设置列位置
  326.             v_coords = []
  327.             v_coords.append(int(left_bound))
  328.             v_coords.append(int(left_bound + regular_column_width * first_column_width_ratio))
  329.             
  330.             for i in range(2, expected_vlines):
  331.                 v_coords.append(int(left_bound + regular_column_width * (i + (first_column_width_ratio - 1))))
  332.         # 8. 检验最终的竖线位置是否合理
  333.         if len(v_coords) == expected_vlines:
  334.             # 计算相邻竖线间距
  335.             spacings = [v_coords[i + 1] - v_coords[i] for i in range(len(v_coords) - 1)]
  336.             avg_spacing = sum(spacings[1:]) / len(spacings[1:])  # 不计入第一列的宽度
  337.             # 检查是否有间距异常的竖线(除第一列外)
  338.             for i in range(1, len(spacings)):
  339.                 if abs(spacings[i] - avg_spacing) > avg_spacing * 0.2:  # 如果间距偏差超过20%
  340.                     print(f"警告: 第{i + 1}和第{i + 2}竖线之间间距异常, 实际:{spacings[i]}, 平均:{avg_spacing}")
  341.                     # 如果是最后一个间距异常,可能是最后一条竖线位置不准
  342.                     if i == len(spacings) - 1:
  343.                         v_coords[-1] = v_coords[-2] + int(avg_spacing)
  344.                         print(f"修正最后一条竖线位置: {v_coords[-1]}")
  345.         # 9. 转换为线段表示
  346.         h_lines = [(0, int(y), width, int(y)) for y in h_coords]
  347.         v_lines = [(int(x), int(table_top), int(x), int(table_bottom)) for x in v_coords]
  348.         # 10. 强制补充缺失的水平线 - 期望有5条水平线(4行表格)
  349.         if len(h_lines) < 5 and len(h_lines) >= 2:
  350.             h_lines.sort(key=lambda x: x[1])
  351.             top_y = int(h_lines[0][1])
  352.             bottom_y = int(h_lines[-1][1])
  353.             height_range = bottom_y - top_y
  354.             # 计算应有的4等分位置
  355.             expected_y_positions = [top_y + int(height_range * i / 4) for i in range(1, 4)]
  356.             # 添加缺失的水平线
  357.             new_h_lines = list(h_lines)
  358.             for y_pos in expected_y_positions:
  359.                 # 检查是否已存在接近该位置的线
  360.                 exist = False
  361.                 for line in h_lines:
  362.                     if abs(line[1] - y_pos) < height // 20:
  363.                         exist = True
  364.                         break
  365.                 if not exist:
  366.                     new_h_lines.append((0, int(y_pos), width, int(y_pos)))
  367.             h_lines = new_h_lines
  368.         # 11. 最终排序
  369.         h_lines = sorted(h_lines, key=lambda x: x[1])
  370.         v_lines = sorted(v_lines, key=lambda x: x[0])
  371.         print(f"最终水平线数量: {len(h_lines)}")
  372.         print(f"最终竖线数量: {len(v_lines)}")
  373.         # 12. 计算并打印竖线间距,用于检验均匀性
  374.         if len(v_lines) > 1:
  375.             spacings = []
  376.             for i in range(len(v_lines) - 1):
  377.                 spacing = v_lines[i + 1][0] - v_lines[i][0]
  378.                 spacings.append(spacing)
  379.             avg_spacing = sum(spacings[1:]) / len(spacings[1:])  # 不计入第一列的宽度
  380.             print(f"竖线平均间距: {avg_spacing:.2f}像素")
  381.             print(f"竖线间距: {spacings}")
  382.         return h_lines, v_lines
  383.     def _cluster_coordinates(self, coords, eps=10):
  384.         """合并相近的坐标"""
  385.         if not coords:
  386.             return []
  387.         coords = sorted(coords)
  388.         clusters = []
  389.         current_cluster = [coords[0]]
  390.         for i in range(1, len(coords)):
  391.             if coords[i] - coords[i - 1] <= eps:
  392.                 current_cluster.append(coords[i])
  393.             else:
  394.                 clusters.append(int(sum(current_cluster) / len(current_cluster)))
  395.                 current_cluster = [coords[i]]
  396.         if current_cluster:
  397.             clusters.append(int(sum(current_cluster) / len(current_cluster)))
  398.         return clusters
  399.     def _visualize_grid(self, image, h_lines, v_lines, output_dir):
  400.         """可视化检测到的网格线并保存结果图像"""
  401.         # 复制原图用于绘制
  402.         result = image.copy()
  403.         if len(result.shape) == 2:
  404.             result = cv2.cvtColor(result, cv2.COLOR_GRAY2BGR)
  405.         # 绘制水平线
  406.         for line in h_lines:
  407.             x1, y1, x2, y2 = line
  408.             cv2.line(result, (int(x1), int(y1)), (int(x2), int(y2)), (0, 0, 255), 2)
  409.         # 绘制垂直线
  410.         for line in v_lines:
  411.             x1, y1, x2, y2 = line
  412.             cv2.line(result, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 2)
  413.         # 绘制交点
  414.         for h_line in h_lines:
  415.             for v_line in v_lines:
  416.                 y = h_line[1]
  417.                 x = v_line[0]
  418.                 cv2.circle(result, (int(x), int(y)), 3, (0, 255, 0), -1)
  419.         
  420.         # 只保存grid_on_image.png
  421.         if output_dir:
  422.             cv2.imwrite(os.path.join(output_dir, "grid_on_image.png"), result)
  423.     def _extract_and_save_cells(self, image, h_lines, v_lines, output_dir, margin=3):
  424.         """提取单元格并保存到输出目录"""
  425.         height, width = image.shape[:2]
  426.         # 确保线条按坐标排序
  427.         h_lines = sorted(h_lines, key=lambda x: x[1])
  428.         v_lines = sorted(v_lines, key=lambda x: x[0])
  429.         # 保存图片路径
  430.         image_paths = []
  431.         # 检查线条数量是否足够
  432.         if len(h_lines) < 4 or len(v_lines) < 10:
  433.             print(f"警告: 线条数量不足(水平线={len(h_lines)}, 垂直线={len(v_lines)})")
  434.             if len(h_lines) < 2 or len(v_lines) < 2:
  435.                 print("错误: 线条数量太少,无法提取任何单元格")
  436.                 return image_paths
  437.         # 记录表格结构
  438.         print(f"表格结构: {len(h_lines)}行, {len(v_lines) - 1}列")
  439.         # 创建题号到行列索引的映射
  440.         question_mapping = {}
  441.         # 第2行是1-13题(列索引从1开始,0列是题号列)
  442.         for i in range(1, 14):
  443.             if i < len(v_lines):
  444.                 question_mapping[i] = (1, i)
  445.         # 第4行是14-25题(列索引从1开始,0列是题号列)
  446.         for i in range(14, 26):
  447.             col_idx = i - 13  # 14题对应第1列,15题对应第2列,...
  448.             if col_idx < len(v_lines) and 3 < len(h_lines):
  449.                 question_mapping[i] = (3, col_idx)
  450.         # 提取每道题的单元格
  451.         saved_questions = []
  452.         for q_num in range(1, 26):
  453.             if q_num not in question_mapping:
  454.                 print(f"题号 {q_num} 没有对应的行列索引映射")
  455.                 continue
  456.             row_idx, col_idx = question_mapping[q_num]
  457.             if row_idx >= len(h_lines) - 1 or col_idx >= len(v_lines) - 1:
  458.                 print(f"题号 {q_num} 的行列索引 ({row_idx}, {col_idx}) 超出表格范围")
  459.                 continue
  460.             try:
  461.                 # 获取单元格边界
  462.                 x1 = int(v_lines[col_idx][0])
  463.                 y1 = int(h_lines[row_idx][1])
  464.                 x2 = int(v_lines[col_idx + 1][0])
  465.                 y2 = int(h_lines[row_idx + 1][1])
  466.                 # 打印单元格信息用于调试
  467.                 if q_num in [1, 4, 13, 14, 25]:  # 打印关键单元格的位置信息
  468.                     print(f"题号 {q_num} 单元格: x1={x1}, y1={y1}, x2={x2}, y2={y2}, 宽={x2 - x1}, 高={y2 - y1}")
  469.                 # 添加边距,避免包含边框线
  470.                 x1_m = min(width - 1, max(0, x1 + margin))
  471.                 y1_m = min(height - 1, max(0, y1 + margin))
  472.                 x2_m = max(0, min(width, x2 - margin))
  473.                 y2_m = max(0, min(height, y2 - margin))
  474.                 # 检查单元格尺寸
  475.                 if x2_m <= x1_m or y2_m <= y1_m or (x2_m - x1_m) < 5 or (y2_m - y1_m) < 5:
  476.                     print(f"跳过无效单元格: 题号 {q_num}, 尺寸过小")
  477.                     continue
  478.                 # 提取单元格
  479.                 cell_img = image[y1_m:y2_m, x1_m:x2_m].copy()
  480.                 # 检查单元格是否为空图像
  481.                 if cell_img.size == 0 or cell_img.shape[0] == 0 or cell_img.shape[1] == 0:
  482.                     print(f"跳过空单元格: 题号 {q_num}")
  483.                     continue
  484.                 # 保存单元格图片
  485.                 cell_filename = f'cell_0{q_num:02d}.png'
  486.                 cell_path = os.path.join(output_dir, cell_filename)
  487.                 cv2.imwrite(cell_path, cell_img)
  488.                 # 添加到路径列表和已保存题号列表
  489.                 image_paths.append(cell_path)
  490.                 saved_questions.append(q_num)
  491.             except Exception as e:
  492.                 print(f"提取题号 {q_num} 时出错: {str(e)}")
  493.         print(f"已保存 {len(saved_questions)} 个单元格,题号: {sorted(saved_questions)}")
  494.         return image_paths
  495. def process_image(input_image_path, output_dir):
  496.     """处理试卷答题区,提取表格并保存单元格"""
  497.     processor = AnswerSheetProcessor()
  498.     return processor.process(input_image_path, output_dir)
  499. def main():
  500.     """主函数:解析命令行参数并执行处理流程"""
  501.     # 解析命令行参数
  502.     parser = argparse.ArgumentParser(description='试卷答题区表格处理工具')
  503.     parser.add_argument('--image', type=str, default="./images/12.jpg", help='输入图像路径')
  504.     parser.add_argument('--output', type=str, default="./output", help='输出目录')
  505.     args = parser.parse_args()
  506.     # 检查图像是否存在
  507.     if not os.path.exists(args.image):
  508.         print(f"图像文件不存在: {args.image}")
  509.         return 1
  510.     # 确保输出目录存在
  511.     os.makedirs(args.output, exist_ok=True)
  512.     print(f"开始处理图像: {args.image}")
  513.     print(f"输出目录: {args.output}")
  514.     # 处理图像
  515.     try:
  516.         image_paths = process_image(args.image, args.output)
  517.         if image_paths:
  518.             print(f"处理成功: 共生成{len(image_paths)}个单元格图片")
  519.             print(f"所有结果已保存到: {args.output}")
  520.             return 0
  521.         else:
  522.             print("处理失败")
  523.             return 1
  524.     except Exception as e:
  525.         print(f"处理过程中发生错误: {str(e)}")
  526.         return 1
  527. if __name__ == "__main__":
  528.     sys.exit(main())
复制代码
5. 应用场景


  • 测验批阅系统:大规模测验的答题卡批阅
  • 教育测评平台:智能化教育测评系统
  • 试卷数字化处置惩罚:将纸质试卷转换为电子数据
  • 教学检测系统:快速评估学生答题环境
6. 算法结果展示


上图是测试的试卷图片,要求提取出填写的答题区。

上图展示了表格网格识别的结果,蓝色线条表现竖线,红色线条表现水平线,绿色点表现线条交点。

上图是从试卷中提取出的答案单位格。
7. 总结与展望

本文先容的试卷答题区表格识别技术,通过计算机视觉算法实现了高效准确的表格定位和单位格提取。该技术有以下优势:

  • 高精度:采用多标准计谋和位置校正算法,提高了表格线识别的精度
  • 高适应性:能够处置惩罚不同样式的试卷答题区
  • 高效率:自动化处置惩罚流程大幅提高了试卷处置惩罚效率
将来我们将继承优化算法,提高对更复杂表格的识别本领,并连合OCR技术实现答案内容的自动识别。
参考资料


  • OpenCV官方文档: https://docs.opencv.org/
  • 数字图像处置惩罚 - 冈萨雷斯
  • 计算机视觉:算法与应用 - Richard Szeliski

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
继续阅读请点击广告

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

×
回复

使用道具 举报

×
登录参与点评抽奖,加入IT实名职场社区
去登录
快速回复 返回顶部 返回列表