目錄
一、項目原理
二、環境準備
三、核心代碼實現
1. 導入必要庫
2. 定義關鍵函數
坐標點排序函數
透視變換函數
輪廓排序函數
圖像顯示函數
3. 主程序實現
圖像預處理
輪廓檢測與答題卡定位
透視變換矯正
答案識別與評分
四、實現效果
本文將介紹如何使用 OpenCV 實現一個簡單的答題卡識別與評分系統,通過圖像處理技術自動識別考生答案并進行評分。
一、項目原理
答題卡識別的核心思路是通過圖像處理技術定位答題卡區域,識別考生填涂的答案,再與標準答案對比進行評分。主要步驟包括:圖像預處理、輪廓檢測、透視變換、答案識別和自動評分。
二、環境準備
pip install numpy opencv-python
三、核心代碼實現
1. 導入必要庫
import numpy as np
import cv2
2. 定義關鍵函數
坐標點排序函數
用于對四邊形的四個頂點進行排序(左上、右上、右下、左下):
def order_points(pts):# 一共有4個坐標點rect = np.zeros(shape=(4, 2), dtype="float32") # 用來存儲排序之后的坐標位置# 按順序找到對應坐標0123分別是 左上,右上,右下,左下s = pts.sum(axis=1) # 對pts矩陣的每一行進行求和操作,(x+y)rect[0] = pts[np.argmin(s)]rect[2] = pts[np.argmax(s)]diff = np.diff(pts, axis=1) # 對pts矩陣的每一行進行求差操作,(y-x)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 = Falsei = 0if method == 'right-to-left' or method == 'bottom-to-top':reverse = Trueif method == 'top-to-bottom' or method == 'bottom-to-top':i = 1boundingBoxes = [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)
3. 主程序實現
圖像預處理
# 讀取圖像
image = cv2.imread(r'./images/test_01.png')
contours_img = image.copy()
# 轉為灰度圖
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 高斯模糊去噪
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
# 邊緣檢測
edged = cv2.Canny(blurred, 75, 200)
輪廓檢測與答題卡定位
# 輪廓檢測
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]
cv2.drawContours(contours_img, cnts, -1, (0, 0, 255), 3)docCnt = None# 根據輪廓大小進行排序,尋找答題卡輪廓(四邊形)
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 = approxbreak
透視變換矯正
# 執行透視變換
warped_t = four_point_transform(image, docCnt.reshape(4, 2))
warped_new = warped_t.copy()
warped = cv2.cvtColor(warped_t, cv2.COLOR_BGR2GRAY)# 閾值處理,將答案區域二值化
thresh = cv2.threshold(warped, 0, 255, cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
答案識別與評分
# 找到每一個圓圈輪廓
cnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2]questionCnts = []
# 篩選出符合條件的答案圓圈輪廓
for c in cnts:(x, y, w, h) = cv2.boundingRect(c)ar = w / float(h)# 根據實際情況指定標準if w >= 20 and h >= 20 and 0.9 <= ar <= 1.1:questionCnts.append(c)# 按照從上到下進行排序
questionCnts = sort_contours(questionCnts, method="top-to-bottom")[0]
correct = 0
ANSWER_KEY = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1} # 正確答案# 每排有5個選項
for (q, i) in enumerate(np.arange(0, len(questionCnts), 5)):cnts = sort_contours(questionCnts[i:i + 5])[0] # 排序bubbled = None# 遍歷每一個選項for (j, c) in enumerate(cnts):# 使用mask來判斷結果mask = np.zeros(thresh.shape, dtype="uint8")cv2.drawContours(mask, [c], -1, 255, -1) # -1表示填充# 通過計算非零點數量來判斷是否選擇這個答案thresh_mask_and = cv2.bitwise_and(thresh, thresh, mask=mask)total = cv2.countNonZero(thresh_mask_and) # 統計灰度值不為0的像素數if bubbled is None or total > bubbled[0]: # 保存灰度值最大的序號(被填涂的選項)bubbled = (total, j)# 對比正確答案color = (0, 0, 255) # 錯誤為紅色k = ANSWER_KEY[q]if k == bubbled[1]: # 判斷正確color = (0, 255, 0) # 正確為綠色correct += 1cv2.drawContours(warped_new, [cnts[k]], -1, color, 3) # 繪制結果# 計算得分
score = (correct / 5.0) * 100
print("[INFO] score: {:.2f}%".format(score))# 顯示得分
cv2.putText(warped_new, "{:.2f}%".format(score), (10, 30),cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv2.imshow("Original", image)
cv2.imshow("Exam", warped_new)
cv2.waitKey(0)
四、實現效果
程序會自動識別答題卡中的填涂區域,與標準答案對比后,用綠色標記正確答案,紅色標記錯誤答案,并在圖像上顯示最終得分。