本文借鑒大佬的(跪求不要舉報我 Orz Orz )
https://www.jianshu.com/p/01f32eb99318
答題卡識别項目實戰
# 預處理
image = cv2.imread(args["image"])
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)
最先複制一下
cv2.GaussianBlur高斯濾波
cv2.Canny邊緣檢測
轉灰階
邊緣檢測
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(contours_img,cnts,-1,(0,0,255),3)
cv_show('contours_img',contours_img)
docCnt = None
輪廓檢測
根據輪廓面積排序
# 確定檢測到了
if len(cnts) > 0:
# 根據輪廓大小進行排序
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 = approx
break
cv2.approxPolyDP 多邊拟合函數
輪廓周長
perimeter = cv2.arcLength(cnt, True)
輪廓面積
area = cv2.contourArea(cnt)
透視變換
分析:截取這個圖檔中的答題卡的矩陣然後通過截取的面機大小進行排序在通過透視變化得到變換後的圖再去截取中間的圓圓
采用自适應的門檻值對其進行處理:
函數還是 cv2.threshold(),但是需要多傳入一個參數( flag): cv2.THRESH_OTSU。這時要把門檻值設為 0。然後算法會找到最優門檻值,這個最優門檻值就是傳回值 retVal。如果不使用 Otsu 二值化,傳回的retVal 值與設定的門檻值相等。
# Otsu's 門檻值處理
thresh = cv2.threshold(warped, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
cv_show('thresh',thresh)
輪廓檢測去檢測園
# 找到每一個圓圈輪廓
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[1]
cv2.drawContours(thresh_Contours,cnts,-1,(0,0,255),3)
cv_show('thresh_Contours',thresh_Contours)
篩選依據實際情況,劃定固定區域,然後進行圓檢測,計算比例,将不符合的去除掉:
questionCnts = []
# 周遊
for c in cnts:
# 計算比例和大小
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
# 根據實際情況指定标準
if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
questionCnts.append(c)
# 按照從上到下進行排序
questionCnts = sort_contours(questionCnts,
method="top-to-bottom")[0]
豎着排序每一題每一題的排序
def sort_contours(cnts, method="left-to-right"):
reverse = False
i = 0
if method == "right-to-left" or method == "bottom-to-top":
reverse = True
if method == "top-to-bottom" or method == "bottom-to-top":
i = 1
boundingBoxes = [cv2.boundingRect(c) for c in cnts]
(cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes),
key=lambda b: b[1][i], reverse=reverse))
按照每排為參照,依次判斷
# 每排有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表示填充
cv_show('mask',mask)
# 通過計算非零點數量來算是否選擇這個答案
mask = cv2.bitwise_and(thresh, thresh, mask=mask)
total = cv2.countNonZero(mask)
# 通過門檻值判斷
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 += 1
# 繪圖
cv2.drawContours(warped, [cnts[k]], -1, color, 3)
最終
代碼連結https://pan.baidu.com/s/1nMUHmnVuIFN1hKWQseo5Ww
提取碼kr8s