python-opencv答题卡识别
时间: 2025-01-12 07:40:32 浏览: 53
### 使用 Python 和 OpenCV 进行答题卡识别
#### 预处理阶段
为了提高后续处理的效果,在开始之前要对输入的答题卡图像做一系列预处理工作。这包括但不限于将彩色图转换成灰度图,通过二值化使图像黑白分明,并去除可能存在的噪声干扰。
```python
import cv2
import numpy as np
def preprocess_image(image_path):
# 加载原始图像并转为灰度模式
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# 应用高斯模糊减少噪音
blurred = cv2.GaussianBlur(image, (5, 5), 0)
# 自适应阈值法进行二值化处理
thresh = cv2.adaptiveThreshold(blurred, 255,
cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY_INV, 11, 2)
return thresh
```
此部分的操作能够有效提升之后轮廓查找以及特征提取的质量[^1]。
#### 轮廓检测与定位
经过初步清理后的图像更易于分析其几何特性。接下来的任务是从中找出代表答题区域的关键形状——通常是矩形框内的选项标记。为此,先寻找整个页面上的所有闭合边界,再从中筛选出最有可能属于答题区的部分。
```python
def find_contours(thresh_img):
contours, _ = cv2.findContours(thresh_img.copy(),
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
contour_data = []
for c in contours:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4: # 只考虑四边形作为候选对象
contour_data.append((approx, cv2.contourArea(approx)))
sorted_contours = sorted(contour_data, key=lambda x:x[1], reverse=True)[:5]
return [c[0] for c in sorted_contours]
```
上述函数会返回按面积大小排列前五名的疑似答题区位置信息列表[^3]。
#### 图像矫正(透视变换)
一旦确定了潜在的目标区域,则可以通过计算四个角点之间的关系来进行视角校正,从而获得更加规整的标准视图用于下一步解析。
```python
def four_point_transform(image, pts):
rect = order_points(pts.reshape(4, 2))
(tl, tr, br, bl) = rect
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 order_points(pts):
rect = np.zeros((4, 2), dtype="float32")
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
```
这段代码实现了基于选定角落坐标的精确变形调整过程。
---
阅读全文
相关推荐




















