目錄
1.答題卡自動批閱整體實現思路
2.關鍵技術步驟與原理
答題卡區域提取
①輪廓檢測并排序
②執行透視變換
③找到每一個圓圈輪廓
④先對所有圓圈輪廓從上到下排序
⑤再通過循環每次只提取出五個輪廓再進行從左到右的排序
3.完整代碼
1.答題卡自動批閱整體實現思路
- 首先,通過圖像處理技術將含答題卡的圖片中的答題區域單獨提取出來,使其變為一個標準的矩形。
- 然后,針對處理后的答題卡區域進行分析,逐一識別每一道題目的各個選項(A, B, C, D, E)是否被學生正確涂黑。
- 最終,根據判斷結果計算出學生的得分,并以百分比和具體答案串等形式展示。
2.關鍵技術步驟與原理
答題卡區域提取
該過程采用“輪廓查找”與“透視變換”。通過灰度化、二值化等預處理,利用cv2.findContours找到答題卡的最外層輪廓,隨后對輪廓進行近似得到四個角點,最后應用透視變換將答題卡區域整齊地裁剪出來。
image=cv2.imread(r'./images/test_04.png')
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)
簡單的預處理操作
①輪廓檢測并排序
- 首先通過輪廓的邊界框(bounding box)對所有選項輪廓進行從大到小的初步排序。
#輪廓檢測
cnts=cv2.findContours(edged.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
cv2.drawContours(contours_img,cnts,-1,(0,0,255),3)
cv_show('contours_img',contours_img)
donCnt=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:donCnt=approxbreak
approx的長度必須為四,得到答題卡區域輪廓的四個近似點坐標矩陣數組
②執行透視變換
#執行透視變換
warped_t=four_point_transform(image,donCnt.reshape(4,2))
warped_new=warped_t.copy()
cv_show('warped_t',warped_t)
二值化
thresh=cv2.threshold(warped,0,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)[1]
cv_show('thresh',thresh)
thresh_Contours=thresh.copy()
③找到每一個圓圈輪廓
先找到所有輪廓
#找到每一個圓圈輪廓
cnts=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
warped_Contours=cv2.drawContours(warped_t,cnts,-1,(0,255,0),1)
cv_show('warped_Contours',warped_Contours)
對所有輪廓做外接矩形條件判斷,篩選出所有圓形答題輪廓共25個
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)
print(len(questionCnts))#25
④先對所有圓圈輪廓從上到下排序
questionCnts=sort_contours(questionCnts,method='top-to-bottom')[0]
correct=0
⑤再通過循環每次只提取出五個輪廓再進行從左到右的排序
#每排有五個選項
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表示填充cv_show('mask',mask)#通過計算非零點數量來算是否選擇這個答案#利用掩膜(mask)進行與操作,只保留mask位置中的內容thresh_mask_and=cv2.bitwise_and(thresh,thresh,mask=mask)cv_show('thresh_mask_and',thresh_mask_and)total=cv2.countNonZero(thresh_mask_and)#統計灰度值不為零的像素數量if bubbled is None or total>bubbled[0]:bubbled=(total,j)#對比正確答案color=(0,0,255)answer=ANSWER_KRY[q]if answer==bubbled[1]:#判斷正確color=(0,255,0)correct+=1cv2.drawContours(warped_new,[cnts[answer]],-1,color,3)cv_show('warpeding',warped_new)
選項識別與答案分析
- 使用逐個建立掩膜(mask)的方式,從原圖中精確摳取出每個選項的圖像。
- 計算摳取出的每個選項區域內的白色像素點數量。
- 通過比較不同選項的白色像素點數量,確定學生實際作答的選項,數量最多的即為作答的區域。
?標準答案比對與評分
- 系統內部維護一個標準答案對照表(answer key),記錄每道題的正確選項。
ANSWER_KRY={0:1,1:4,2:0,3:3,4:1}#正確答案
- 將程序識別出的答案與標準答案進行比對。
- 若答案正確,則計為1分,并使用綠色邊框對正確選項進行標注;若答案錯誤,則不加分,并用紅色邊框標注正確選項。
- 最終,系統將根據總分和題目數量計算出最終得分并在圖片上顯示。
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)
cv_show('Original',image)
cv_show('Exam',warped_new)#[INFO] score:20.00%
3.完整代碼
import cv2
import numpy as npdef order_points(pts):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)#M是獲取到的轉換之間的關系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 a:a[1][i],reverse=reverse))return cnts,boundingBoxes
def cv_show(name,img):cv2.imshow(name,img)cv2.waitKey(0)ANSWER_KRY={0:1,1:4,2:0,3:3,4:1}#正確答案image=cv2.imread(r'./images/test_04.png')
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)
#輪廓檢測
cnts=cv2.findContours(edged.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
cv2.drawContours(contours_img,cnts,-1,(0,0,255),3)
cv_show('contours_img',contours_img)
donCnt=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:donCnt=approxbreak
#執行透視變換
warped_t=four_point_transform(image,donCnt.reshape(4,2))
warped_new=warped_t.copy()
cv_show('warped_t',warped_t)
warped=cv2.cvtColor(warped_t,cv2.COLOR_BGR2GRAY)
thresh=cv2.threshold(warped,0,255,cv2.THRESH_BINARY_INV|cv2.THRESH_OTSU)[1]
cv_show('thresh',thresh)
thresh_Contours=thresh.copy()
#找到每一個圓圈輪廓
cnts=cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]
warped_Contours=cv2.drawContours(warped_t,cnts,-1,(0,255,0),1)
cv_show('warped_Contours',warped_Contours)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)
print(len(questionCnts))
#按照從上到下進行排序
questionCnts=sort_contours(questionCnts,method='top-to-bottom')[0]
correct=0
#每排有五個選項
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表示填充cv_show('mask',mask)#通過計算非零點數量來算是否選擇這個答案#利用掩膜(mask)進行與操作,只保留mask位置中的內容thresh_mask_and=cv2.bitwise_and(thresh,thresh,mask=mask)cv_show('thresh_mask_and',thresh_mask_and)total=cv2.countNonZero(thresh_mask_and)#統計灰度值不為零的像素數量if bubbled is None or total>bubbled[0]:bubbled=(total,j)#對比正確答案color=(0,0,255)answer=ANSWER_KRY[q]if answer==bubbled[1]:#判斷正確color=(0,255,0)correct+=1cv2.drawContours(warped_new,[cnts[answer]],-1,color,3)cv_show('warpeding',warped_new)
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)
cv_show('Original',image)
cv_show('Exam',warped_new)