最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

使用?OpenCV-Python?識(shí)別答題卡判卷功能

 更新時(shí)間:2021年12月21日 15:08:03   作者:糖公子沒(méi)來(lái)過(guò)  
這篇文章主要介紹了使用?OpenCV-Python?識(shí)別答題卡判卷,本文分步驟通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

任務(wù)

識(shí)別用相機(jī)拍下來(lái)的答題卡,并判斷最終得分(假設(shè)正確答案是B, E, A, D, B)

主要步驟

  1. 輪廓識(shí)別——答題卡邊緣識(shí)別
  2. 透視變換——提取答題卡主體
  3. 輪廓識(shí)別——識(shí)別出所有圓形選項(xiàng),剔除無(wú)關(guān)輪廓
  4. 檢測(cè)每一行選擇的是哪一項(xiàng),并將結(jié)果儲(chǔ)存起來(lái),記錄正確的個(gè)數(shù)
  5. 計(jì)算最終得分并在圖中標(biāo)注

分步實(shí)現(xiàn)

輪廓識(shí)別——答題卡邊緣識(shí)別

輸入圖像

import cv2 as cv
import numpy as np
 
# 正確答案
right_key = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
 
# 輸入圖像
img = cv.imread('./images/test_01.jpg')
img_copy = img.copy()
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cvshow('img-gray', img_gray)

圖像預(yù)處理

# 圖像預(yù)處理
# 高斯降噪
img_gaussian = cv.GaussianBlur(img_gray, (5, 5), 1)
cvshow('gaussianblur', img_gaussian)
# canny邊緣檢測(cè)
img_canny = cv.Canny(img_gaussian, 80, 150)
cvshow('canny', img_canny)

?

?

輪廓識(shí)別——答題卡邊緣識(shí)別

# 輪廓識(shí)別——答題卡邊緣識(shí)別
cnts, hierarchy = cv.findContours(img_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img_copy, cnts, -1, (0, 0, 255), 3)
cvshow('contours-show', img_copy)

透視變換——提取答題卡主體

對(duì)每個(gè)輪廓進(jìn)行擬合,將多邊形輪廓變?yōu)樗倪呅?/p>

docCnt = None
 
# 確保檢測(cè)到了
if len(cnts) > 0:
    # 根據(jù)輪廓大小進(jìn)行排序
    cnts = sorted(cnts, key=cv.contourArea, reverse=True)
 
    # 遍歷每一個(gè)輪廓
    for c in cnts:
        # 近似
        peri = cv.arcLength(c, True)
        # arclength 計(jì)算一段曲線的長(zhǎng)度或者閉合曲線的周長(zhǎng);
        # 第一個(gè)參數(shù)輸入一個(gè)二維向量,第二個(gè)參數(shù)表示計(jì)算曲線是否閉合
 
        approx = cv.approxPolyDP(c, 0.02 * peri, True)
        # 用一條頂點(diǎn)較少的曲線/多邊形來(lái)近似曲線/多邊形,以使它們之間的距離<=指定的精度;
        # c是需要近似的曲線,0.02*peri是精度的最大值,True表示曲線是閉合的
 
        # 準(zhǔn)備做透視變換
        if len(approx) == 4:
            docCnt = approx
            break

透視變換——提取答題卡主體

# 透視變換——提取答題卡主體
docCnt = docCnt.reshape(4, 2)
warped = four_point_transform(img_gray, docCnt)
cvshow('warped', warped)
def four_point_transform(img, four_points):
    rect = order_points(four_points)
    (tl, tr, br, bl) = rect
 
    # 計(jì)算輸入的w和h的值
    widthA = np.sqrt((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)
    widthB = np.sqrt((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)
    maxWidth = max(int(widthA), int(widthB))
 
    heightA = np.sqrt((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)
    heightB = np.sqrt((tr[0] - br[0]) ** 2 + (tr[1] - br[1]) ** 2)
    maxHeight = max(int(heightA), int(heightB))
 
    # 變換后對(duì)應(yīng)的坐標(biāo)位置
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype='float32')
 
    # 最主要的函數(shù)就是 cv2.getPerspectiveTransform(rect, dst) 和 cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    M = cv.getPerspectiveTransform(rect, dst)
    warped = cv.warpPerspective(img, M, (maxWidth, maxHeight))
    return warped
 
 
def order_points(points):
    res = np.zeros((4, 2), dtype='float32')
    # 按照從前往后0,1,2,3分別表示左上、右上、右下、左下的順序?qū)oints中的數(shù)填入res中
 
    # 將四個(gè)坐標(biāo)x與y相加,和最大的那個(gè)是右下角的坐標(biāo),最小的那個(gè)是左上角的坐標(biāo)
    sum_hang = points.sum(axis=1)
    res[0] = points[np.argmin(sum_hang)]
    res[2] = points[np.argmax(sum_hang)]
 
    # 計(jì)算坐標(biāo)x與y的離散插值np.diff()
    diff = np.diff(points, axis=1)
    res[1] = points[np.argmin(diff)]
    res[3] = points[np.argmax(diff)]
 
    # 返回result
    return res

輪廓識(shí)別——識(shí)別出選項(xiàng)

# 輪廓識(shí)別——識(shí)別出選項(xiàng)
thresh = cv.threshold(warped, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]
cvshow('thresh', thresh)
thresh_cnts, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
w_copy = warped.copy()
cv.drawContours(w_copy, thresh_cnts, -1, (0, 0, 255), 2)
cvshow('warped_contours', w_copy)
 
questionCnts = []
# 遍歷,挑出選項(xiàng)的cnts
for c in thresh_cnts:
    (x, y, w, h) = cv.boundingRect(c)
    ar = w / float(h)
    # 根據(jù)實(shí)際情況指定標(biāo)準(zhǔn)
    if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
        questionCnts.append(c)
 
# 檢查是否挑出了選項(xiàng)
w_copy2 = warped.copy()
cv.drawContours(w_copy2, questionCnts, -1, (0, 0, 255), 2)
cvshow('questionCnts', w_copy2)

成功將無(wú)關(guān)輪廓剔除

檢測(cè)每一行選擇的是哪一項(xiàng),并將結(jié)果儲(chǔ)存起來(lái),記錄正確的個(gè)數(shù)

# 檢測(cè)每一行選擇的是哪一項(xiàng),并將結(jié)果儲(chǔ)存在元組bubble中,記錄正確的個(gè)數(shù)correct
# 按照從上到下t2b對(duì)輪廓進(jìn)行排序
questionCnts = sort_contours(questionCnts, method="t2b")[0]
correct = 0
# 每行有5個(gè)選項(xiàng)
for (i, q) in enumerate(np.arange(0, len(questionCnts), 5)):
    # 排序
    cnts = sort_contours(questionCnts[q:q+5])[0]
 
    bubble = None
    # 得到每一個(gè)選項(xiàng)的mask并填充,與正確答案進(jìn)行按位與操作獲得重合點(diǎn)數(shù)
    for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype='uint8')
        cv.drawContours(mask, [c], -1, 255, -1)
        # cvshow('mask', mask)
 
        # 通過(guò)按位與操作得到thresh與mask重合部分的像素?cái)?shù)量
        bitand = cv.bitwise_and(thresh, thresh, mask=mask)
        totalPixel = cv.countNonZero(bitand)
 
        if bubble is None or bubble[0] < totalPixel:
            bubble = (totalPixel, j)
 
    k = bubble[1]
    color = (0, 0, 255)
    if k == right_key[i]:
        correct += 1
        color = (0, 255, 0)
 
    # 繪圖
    cv.drawContours(warped, [cnts[right_key[i]]], -1, color, 3)
    cvshow('final', warped)
def sort_contours(contours, method="l2r"):
    # 用于給輪廓排序,l2r, r2l, t2b, b2t
    reverse = False
    i = 0
    if method == "r2l" or method == "b2t":
        reverse = True
    if method == "t2b" or method == "b2t":
        i = 1
 
    boundingBoxes = [cv.boundingRect(c) for c in contours]
    (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes), key=lambda a: a[1][i], reverse=reverse))
    return contours, boundingBoxes

?

用透過(guò)mask的像素的個(gè)數(shù)來(lái)判斷考生選擇的是哪個(gè)選項(xiàng)

計(jì)算最終得分并在圖中標(biāo)注

# 計(jì)算最終得分并在圖中標(biāo)注
score = (correct / 5.0) * 100
print(f"Score: {score}%")
cv.putText(warped, f"Score: {score}%", (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv.imshow("Original", img)
cv.imshow("Exam", warped)
cv.waitKey(0)

完整代碼

import cv2 as cv
import numpy as np
 
 
def cvshow(name, img):
    cv.imshow(name, img)
    cv.waitKey(0)
    cv.destroyAllWindows()
 
def four_point_transform(img, four_points):
    rect = order_points(four_points)
    (tl, tr, br, bl) = rect
 
    # 計(jì)算輸入的w和h的值
    widthA = np.sqrt((tr[0] - tl[0]) ** 2 + (tr[1] - tl[1]) ** 2)
    widthB = np.sqrt((br[0] - bl[0]) ** 2 + (br[1] - bl[1]) ** 2)
    maxWidth = max(int(widthA), int(widthB))
 
    heightA = np.sqrt((tl[0] - bl[0]) ** 2 + (tl[1] - bl[1]) ** 2)
    heightB = np.sqrt((tr[0] - br[0]) ** 2 + (tr[1] - br[1]) ** 2)
    maxHeight = max(int(heightA), int(heightB))
 
    # 變換后對(duì)應(yīng)的坐標(biāo)位置
    dst = np.array([
        [0, 0],
        [maxWidth - 1, 0],
        [maxWidth - 1, maxHeight - 1],
        [0, maxHeight - 1]], dtype='float32')
 
    # 最主要的函數(shù)就是 cv2.getPerspectiveTransform(rect, dst) 和 cv2.warpPerspective(image, M, (maxWidth, maxHeight))
    M = cv.getPerspectiveTransform(rect, dst)
    warped = cv.warpPerspective(img, M, (maxWidth, maxHeight))
    return warped
 
 
def order_points(points):
    res = np.zeros((4, 2), dtype='float32')
    # 按照從前往后0,1,2,3分別表示左上、右上、右下、左下的順序?qū)oints中的數(shù)填入res中
 
    # 將四個(gè)坐標(biāo)x與y相加,和最大的那個(gè)是右下角的坐標(biāo),最小的那個(gè)是左上角的坐標(biāo)
    sum_hang = points.sum(axis=1)
    res[0] = points[np.argmin(sum_hang)]
    res[2] = points[np.argmax(sum_hang)]
 
    # 計(jì)算坐標(biāo)x與y的離散插值np.diff()
    diff = np.diff(points, axis=1)
    res[1] = points[np.argmin(diff)]
    res[3] = points[np.argmax(diff)]
 
    # 返回result
    return res
 
 
def sort_contours(contours, method="l2r"):
    # 用于給輪廓排序,l2r, r2l, t2b, b2t
    reverse = False
    i = 0
    if method == "r2l" or method == "b2t":
        reverse = True
    if method == "t2b" or method == "b2t":
        i = 1
 
    boundingBoxes = [cv.boundingRect(c) for c in contours]
    (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes), key=lambda a: a[1][i], reverse=reverse))
    return contours, boundingBoxes
 
# 正確答案
right_key = {0: 1, 1: 4, 2: 0, 3: 3, 4: 1}
 
# 輸入圖像
img = cv.imread('./images/test_01.jpg')
img_copy = img.copy()
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
cvshow('img-gray', img_gray)
 
# 圖像預(yù)處理
# 高斯降噪
img_gaussian = cv.GaussianBlur(img_gray, (5, 5), 1)
cvshow('gaussianblur', img_gaussian)
# canny邊緣檢測(cè)
img_canny = cv.Canny(img_gaussian, 80, 150)
cvshow('canny', img_canny)
 
# 輪廓識(shí)別——答題卡邊緣識(shí)別
cnts, hierarchy = cv.findContours(img_canny, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(img_copy, cnts, -1, (0, 0, 255), 3)
cvshow('contours-show', img_copy)
 
docCnt = None
 
# 確保檢測(cè)到了
if len(cnts) > 0:
    # 根據(jù)輪廓大小進(jìn)行排序
    cnts = sorted(cnts, key=cv.contourArea, reverse=True)
 
    # 遍歷每一個(gè)輪廓
    for c in cnts:
        # 近似
        peri = cv.arcLength(c, True)  # arclength 計(jì)算一段曲線的長(zhǎng)度或者閉合曲線的周長(zhǎng);
        # 第一個(gè)參數(shù)輸入一個(gè)二維向量,第二個(gè)參數(shù)表示計(jì)算曲線是否閉合
 
        approx = cv.approxPolyDP(c, 0.02 * peri, True)
        # 用一條頂點(diǎn)較少的曲線/多邊形來(lái)近似曲線/多邊形,以使它們之間的距離<=指定的精度;
        # c是需要近似的曲線,0.02*peri是精度的最大值,True表示曲線是閉合的
 
        # 準(zhǔn)備做透視變換
        if len(approx) == 4:
            docCnt = approx
            break
 
 
# 透視變換——提取答題卡主體
docCnt = docCnt.reshape(4, 2)
warped = four_point_transform(img_gray, docCnt)
cvshow('warped', warped)
 
 
# 輪廓識(shí)別——識(shí)別出選項(xiàng)
thresh = cv.threshold(warped, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)[1]
cvshow('thresh', thresh)
thresh_cnts, _ = cv.findContours(thresh, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
w_copy = warped.copy()
cv.drawContours(w_copy, thresh_cnts, -1, (0, 0, 255), 2)
cvshow('warped_contours', w_copy)
 
questionCnts = []
# 遍歷,挑出選項(xiàng)的cnts
for c in thresh_cnts:
    (x, y, w, h) = cv.boundingRect(c)
    ar = w / float(h)
    # 根據(jù)實(shí)際情況指定標(biāo)準(zhǔn)
    if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
        questionCnts.append(c)
 
# 檢查是否挑出了選項(xiàng)
w_copy2 = warped.copy()
cv.drawContours(w_copy2, questionCnts, -1, (0, 0, 255), 2)
cvshow('questionCnts', w_copy2)
 
 
# 檢測(cè)每一行選擇的是哪一項(xiàng),并將結(jié)果儲(chǔ)存在元組bubble中,記錄正確的個(gè)數(shù)correct
# 按照從上到下t2b對(duì)輪廓進(jìn)行排序
questionCnts = sort_contours(questionCnts, method="t2b")[0]
correct = 0
# 每行有5個(gè)選項(xiàng)
for (i, q) in enumerate(np.arange(0, len(questionCnts), 5)):
    # 排序
    cnts = sort_contours(questionCnts[q:q+5])[0]
 
    bubble = None
    # 得到每一個(gè)選項(xiàng)的mask并填充,與正確答案進(jìn)行按位與操作獲得重合點(diǎn)數(shù)
    for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype='uint8')
        cv.drawContours(mask, [c], -1, 255, -1)
        cvshow('mask', mask)
 
        # 通過(guò)按位與操作得到thresh與mask重合部分的像素?cái)?shù)量
        bitand = cv.bitwise_and(thresh, thresh, mask=mask)
        totalPixel = cv.countNonZero(bitand)
 
        if bubble is None or bubble[0] < totalPixel:
            bubble = (totalPixel, j)
 
    k = bubble[1]
    color = (0, 0, 255)
    if k == right_key[i]:
        correct += 1
        color = (0, 255, 0)
 
    # 繪圖
    cv.drawContours(warped, [cnts[right_key[i]]], -1, color, 3)
    cvshow('final', warped)
 
 
# 計(jì)算最終得分并在圖中標(biāo)注
score = (correct / 5.0) * 100
print(f"Score: {score}%")
cv.putText(warped, f"Score: {score}%", (10, 30), cv.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv.imshow("Original", img)
cv.imshow("Exam", warped)
cv.waitKey(0)
 
 

到此這篇關(guān)于使用?OpenCV-Python?識(shí)別答題卡判卷的文章就介紹到這了,更多相關(guān)OpenCV?Python?識(shí)別答題卡判卷內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Python數(shù)據(jù)處理pandas讀寫(xiě)操作IO工具CSV解析

    Python數(shù)據(jù)處理pandas讀寫(xiě)操作IO工具CSV解析

    這篇文章主要為大家介紹了Python?pandas數(shù)據(jù)讀寫(xiě)操作IO工具之CSV使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-06-06
  • 分享10個(gè)有趣的Python程序

    分享10個(gè)有趣的Python程序

    這篇文章主要給大家分享的是10個(gè)有趣的Python程序,Python程序有許多模塊和第三方包,這非常有助于高效編程,所以了解這些模塊的正確使用方法是很重要的,下面詳細(xì)內(nèi)容,需要的小伙伴可以參考一下
    2022-02-02
  • 簡(jiǎn)單談?wù)凱ython中的json與pickle

    簡(jiǎn)單談?wù)凱ython中的json與pickle

    下面小編就為大家?guī)?lái)一篇簡(jiǎn)單談?wù)凱ython中的json與pickle。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-07-07
  • python學(xué)習(xí)之SpaCy庫(kù)的高級(jí)特性詳解

    python學(xué)習(xí)之SpaCy庫(kù)的高級(jí)特性詳解

    在之前的文章中,我們介紹了SpaCy庫(kù)的一些基本概念和功能,在這篇文章中,我們將深入學(xué)習(xí)一些更高級(jí)的特性,包括詞向量、依賴性解析、和自定義組件
    2023-07-07
  • Python wxPython庫(kù)使用wx.ListBox創(chuàng)建列表框示例

    Python wxPython庫(kù)使用wx.ListBox創(chuàng)建列表框示例

    這篇文章主要介紹了Python wxPython庫(kù)使用wx.ListBox創(chuàng)建列表框,結(jié)合實(shí)例形式分析了wxPython庫(kù)使用wx.ListBox創(chuàng)建列表框的簡(jiǎn)單實(shí)現(xiàn)方法及ListBox函數(shù)相關(guān)選項(xiàng)的功能,需要的朋友可以參考下
    2018-09-09
  • django2.0擴(kuò)展用戶字段示例

    django2.0擴(kuò)展用戶字段示例

    今天小編就為大家分享一篇關(guān)于django2.0擴(kuò)展用戶字段示例,小編覺(jué)得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來(lái)看看吧
    2019-02-02
  • 關(guān)于keras中的Reshape用法

    關(guān)于keras中的Reshape用法

    這篇文章主要介紹了關(guān)于keras中的Reshape用法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-07-07
  • 淺談Django自定義模板標(biāo)簽template_tags的用處

    淺談Django自定義模板標(biāo)簽template_tags的用處

    這篇文章主要介紹了淺談Django自定義模板標(biāo)簽template_tags的用處,具有一定借鑒價(jià)值,需要的朋友可以參考下。
    2017-12-12
  • 詳解python項(xiàng)目實(shí)戰(zhàn):模擬登陸CSDN

    詳解python項(xiàng)目實(shí)戰(zhàn):模擬登陸CSDN

    這篇文章主要介紹了python項(xiàng)目實(shí)戰(zhàn):模擬登陸CSDN,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-04-04
  • python爬蟲(chóng) 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解

    python爬蟲(chóng) 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解

    下面小編就為大家?guī)?lái)一篇python爬蟲(chóng) 正則表達(dá)式使用技巧及爬取個(gè)人博客的實(shí)例講解。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-10-10

最新評(píng)論

容城县| 柘荣县| 恭城| 伊宁县| 英山县| 濮阳市| 宿州市| 察隅县| 桦甸市| 绥芬河市| 长阳| 滦平县| 兴和县| 孙吴县| 商河县| 余干县| 桃园市| 治多县| 安西县| 陇川县| 郁南县| 正宁县| 井研县| 阳新县| 阿克苏市| 图片| 军事| 仪征市| 长寿区| 遂平县| 横山县| 葵青区| 石首市| 呼玛县| 甘德县| 慈利县| 海城市| 涡阳县| 遵义县| 浮山县| 北流市|