How to read a bubble sheet using CV2 in python? I'm facing some issues reading contours using cv2Which Python memory profiler is recommended?How do I get time of a Python program's execution?Python progression path - From apprentice to guruHow to read a large file, line by line, in PythonWhy is reading lines from stdin much slower in C++ than Python?How does one convert a grayscale image to RGB in OpenCV (Python) for visualizing contours after processing an image in binary?Problems in traversing contours in python using cv2 libraryColor of center of contour cv2 pythonProblems drawing a specific contour using cv2.drawContours() Python 3Python cv2 edge and contour detection

How well known and how commonly used was Huffman coding in 1979?

Why does the A-4 Skyhawk sit nose-up when on ground?

Why is C++ initial allocation so much larger than C's?

Do I recheck baggage at stopovers MCI-SEA-ICN-SGN? Delta and Korean Air

The impact of an intelligent and (mostly) hostile flying race on weapons and armor

When is it ok to add filler to a story?

Declining an offer to present a poster instead of a paper

How many satellites can stay in a Lagrange point?

What do you call the action of someone tackling a stronger person?

Why is the Turkish president's surname spelt in Russian as Эрдоган, with г?

Why is Madam Hooch not a professor?

Links to webpages in books

Is there a short way to compare many values mutually at same time without using multiple 'AND'-s?

How can I repair scratches on a painted French door?

Does image quality of the lens affect "focus and recompose" technique?

Pull-up sequence accumulator counter

Firefox Arm64 available but RapsPi 3B+ still 32 bit

Content builder HTTPS

Does anycast addressing add additional latency in any way?

Is it OK to bottle condition using previously contaminated bottles?

How many codes are possible?

"It will become the talk of Paris" - translation into French

Is adding a new player (or players) a DM decision, or a group decision?

Why isn’t the tax system continuous rather than bracketed?



How to read a bubble sheet using CV2 in python? I'm facing some issues reading contours using cv2


Which Python memory profiler is recommended?How do I get time of a Python program's execution?Python progression path - From apprentice to guruHow to read a large file, line by line, in PythonWhy is reading lines from stdin much slower in C++ than Python?How does one convert a grayscale image to RGB in OpenCV (Python) for visualizing contours after processing an image in binary?Problems in traversing contours in python using cv2 libraryColor of center of contour cv2 pythonProblems drawing a specific contour using cv2.drawContours() Python 3Python cv2 edge and contour detection






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








-1















enter image description hereI want to read a bubble sheet in python using cv2. But my code is not giving me exact contours or exact count of circles. I










share|improve this question
























  • What have you tried so far? We're not going to write your code for you!

    – Ari Cooper-Davis
    Mar 25 at 11:57

















-1















enter image description hereI want to read a bubble sheet in python using cv2. But my code is not giving me exact contours or exact count of circles. I










share|improve this question
























  • What have you tried so far? We're not going to write your code for you!

    – Ari Cooper-Davis
    Mar 25 at 11:57













-1












-1








-1








enter image description hereI want to read a bubble sheet in python using cv2. But my code is not giving me exact contours or exact count of circles. I










share|improve this question
















enter image description hereI want to read a bubble sheet in python using cv2. But my code is not giving me exact contours or exact count of circles. I







python cv2






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 25 at 10:57







Junaid Bin Tariq

















asked Mar 25 at 10:19









Junaid Bin TariqJunaid Bin Tariq

11 bronze badge




11 bronze badge












  • What have you tried so far? We're not going to write your code for you!

    – Ari Cooper-Davis
    Mar 25 at 11:57

















  • What have you tried so far? We're not going to write your code for you!

    – Ari Cooper-Davis
    Mar 25 at 11:57
















What have you tried so far? We're not going to write your code for you!

– Ari Cooper-Davis
Mar 25 at 11:57





What have you tried so far? We're not going to write your code for you!

– Ari Cooper-Davis
Mar 25 at 11:57












1 Answer
1






active

oldest

votes


















0














def normalize(im):
return cv2.normalize(im, np.zeros(im.shape), 0, 255,norm_type=cv2.NORM_MINMAX)

# load the image and show it
image = cv2.imread("/home/junaid/PycharmProjects/omr/img/scan_score.jpg")

cropped_1 = image[1278:2082, 517:1006].copy()
cv2.imshow("cropped", cropped_1)

edges = cv2.Canny(cropped_1, 100, 200)

blurred = cv2.GaussianBlur(cropped_1, (11, 11), 10)

im = normalize(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY))

ret, im = cv2.threshold(im, 160, 255, cv2.THRESH_BINARY)

thresh = cv2.threshold(im, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


cnts = imutils.grab_contours(cnts)

# print(cnts)

questionCnts = []

for c in cnts:
ar = cv2.contourArea(c)
cv2.drawContours(thresh, c, -1,(255,0,0),3)
if ar>=2800 and ar<= 2900:
questionCnts.append(c)
# if h >= 42 or h <= 44 and w>=56 or w <= 59 and ar>=1.4 and ar<=1.5:
# questionCnts.append(c)

# print(len(cnts))
print(len(questionCnts))

questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")
[0]
# print(questionCnts)

correct = 0

for (q,i) in enumerate(np.arange(0, len(questionCnts), 4)):
cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
bubbled = None
# print(cnts)

for (j, c) in enumerate(cnts):
mask = np.zeros(thresh.shape, dtype="uint8")
print(mask)
cv2.drawContours(mask, [c], -1, (255,0,0), 1)

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 = 0

if k == bubbled[1]:
color = (0, 255, 0)
correct += 1
print("correct", correct)

cv2.drawContours(im, [cnts[k]], -1, color, 3)


# grab the test taker
score = (correct / 13.0) * 100
print("[INFO] score: :.2f%".format(score))
cv2.putText(im, ":.2f%".format(score), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
# cv2.imshow("Original", image)
cv2.imshow("Exam", im)

cv2.waitKey(0)





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335560%2fhow-to-read-a-bubble-sheet-using-cv2-in-python-im-facing-some-issues-reading-c%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    def normalize(im):
    return cv2.normalize(im, np.zeros(im.shape), 0, 255,norm_type=cv2.NORM_MINMAX)

    # load the image and show it
    image = cv2.imread("/home/junaid/PycharmProjects/omr/img/scan_score.jpg")

    cropped_1 = image[1278:2082, 517:1006].copy()
    cv2.imshow("cropped", cropped_1)

    edges = cv2.Canny(cropped_1, 100, 200)

    blurred = cv2.GaussianBlur(cropped_1, (11, 11), 10)

    im = normalize(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY))

    ret, im = cv2.threshold(im, 160, 255, cv2.THRESH_BINARY)

    thresh = cv2.threshold(im, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

    cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


    cnts = imutils.grab_contours(cnts)

    # print(cnts)

    questionCnts = []

    for c in cnts:
    ar = cv2.contourArea(c)
    cv2.drawContours(thresh, c, -1,(255,0,0),3)
    if ar>=2800 and ar<= 2900:
    questionCnts.append(c)
    # if h >= 42 or h <= 44 and w>=56 or w <= 59 and ar>=1.4 and ar<=1.5:
    # questionCnts.append(c)

    # print(len(cnts))
    print(len(questionCnts))

    questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")
    [0]
    # print(questionCnts)

    correct = 0

    for (q,i) in enumerate(np.arange(0, len(questionCnts), 4)):
    cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
    bubbled = None
    # print(cnts)

    for (j, c) in enumerate(cnts):
    mask = np.zeros(thresh.shape, dtype="uint8")
    print(mask)
    cv2.drawContours(mask, [c], -1, (255,0,0), 1)

    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 = 0

    if k == bubbled[1]:
    color = (0, 255, 0)
    correct += 1
    print("correct", correct)

    cv2.drawContours(im, [cnts[k]], -1, color, 3)


    # grab the test taker
    score = (correct / 13.0) * 100
    print("[INFO] score: :.2f%".format(score))
    cv2.putText(im, ":.2f%".format(score), (10, 30),
    cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
    # cv2.imshow("Original", image)
    cv2.imshow("Exam", im)

    cv2.waitKey(0)





    share|improve this answer



























      0














      def normalize(im):
      return cv2.normalize(im, np.zeros(im.shape), 0, 255,norm_type=cv2.NORM_MINMAX)

      # load the image and show it
      image = cv2.imread("/home/junaid/PycharmProjects/omr/img/scan_score.jpg")

      cropped_1 = image[1278:2082, 517:1006].copy()
      cv2.imshow("cropped", cropped_1)

      edges = cv2.Canny(cropped_1, 100, 200)

      blurred = cv2.GaussianBlur(cropped_1, (11, 11), 10)

      im = normalize(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY))

      ret, im = cv2.threshold(im, 160, 255, cv2.THRESH_BINARY)

      thresh = cv2.threshold(im, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

      cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


      cnts = imutils.grab_contours(cnts)

      # print(cnts)

      questionCnts = []

      for c in cnts:
      ar = cv2.contourArea(c)
      cv2.drawContours(thresh, c, -1,(255,0,0),3)
      if ar>=2800 and ar<= 2900:
      questionCnts.append(c)
      # if h >= 42 or h <= 44 and w>=56 or w <= 59 and ar>=1.4 and ar<=1.5:
      # questionCnts.append(c)

      # print(len(cnts))
      print(len(questionCnts))

      questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")
      [0]
      # print(questionCnts)

      correct = 0

      for (q,i) in enumerate(np.arange(0, len(questionCnts), 4)):
      cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
      bubbled = None
      # print(cnts)

      for (j, c) in enumerate(cnts):
      mask = np.zeros(thresh.shape, dtype="uint8")
      print(mask)
      cv2.drawContours(mask, [c], -1, (255,0,0), 1)

      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 = 0

      if k == bubbled[1]:
      color = (0, 255, 0)
      correct += 1
      print("correct", correct)

      cv2.drawContours(im, [cnts[k]], -1, color, 3)


      # grab the test taker
      score = (correct / 13.0) * 100
      print("[INFO] score: :.2f%".format(score))
      cv2.putText(im, ":.2f%".format(score), (10, 30),
      cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
      # cv2.imshow("Original", image)
      cv2.imshow("Exam", im)

      cv2.waitKey(0)





      share|improve this answer

























        0












        0








        0







        def normalize(im):
        return cv2.normalize(im, np.zeros(im.shape), 0, 255,norm_type=cv2.NORM_MINMAX)

        # load the image and show it
        image = cv2.imread("/home/junaid/PycharmProjects/omr/img/scan_score.jpg")

        cropped_1 = image[1278:2082, 517:1006].copy()
        cv2.imshow("cropped", cropped_1)

        edges = cv2.Canny(cropped_1, 100, 200)

        blurred = cv2.GaussianBlur(cropped_1, (11, 11), 10)

        im = normalize(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY))

        ret, im = cv2.threshold(im, 160, 255, cv2.THRESH_BINARY)

        thresh = cv2.threshold(im, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

        cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


        cnts = imutils.grab_contours(cnts)

        # print(cnts)

        questionCnts = []

        for c in cnts:
        ar = cv2.contourArea(c)
        cv2.drawContours(thresh, c, -1,(255,0,0),3)
        if ar>=2800 and ar<= 2900:
        questionCnts.append(c)
        # if h >= 42 or h <= 44 and w>=56 or w <= 59 and ar>=1.4 and ar<=1.5:
        # questionCnts.append(c)

        # print(len(cnts))
        print(len(questionCnts))

        questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")
        [0]
        # print(questionCnts)

        correct = 0

        for (q,i) in enumerate(np.arange(0, len(questionCnts), 4)):
        cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
        bubbled = None
        # print(cnts)

        for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype="uint8")
        print(mask)
        cv2.drawContours(mask, [c], -1, (255,0,0), 1)

        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 = 0

        if k == bubbled[1]:
        color = (0, 255, 0)
        correct += 1
        print("correct", correct)

        cv2.drawContours(im, [cnts[k]], -1, color, 3)


        # grab the test taker
        score = (correct / 13.0) * 100
        print("[INFO] score: :.2f%".format(score))
        cv2.putText(im, ":.2f%".format(score), (10, 30),
        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
        # cv2.imshow("Original", image)
        cv2.imshow("Exam", im)

        cv2.waitKey(0)





        share|improve this answer













        def normalize(im):
        return cv2.normalize(im, np.zeros(im.shape), 0, 255,norm_type=cv2.NORM_MINMAX)

        # load the image and show it
        image = cv2.imread("/home/junaid/PycharmProjects/omr/img/scan_score.jpg")

        cropped_1 = image[1278:2082, 517:1006].copy()
        cv2.imshow("cropped", cropped_1)

        edges = cv2.Canny(cropped_1, 100, 200)

        blurred = cv2.GaussianBlur(cropped_1, (11, 11), 10)

        im = normalize(cv2.cvtColor(blurred, cv2.COLOR_BGR2GRAY))

        ret, im = cv2.threshold(im, 160, 255, cv2.THRESH_BINARY)

        thresh = cv2.threshold(im, 0, 255,cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]

        cnts = cv2.findContours(thresh.copy(), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)


        cnts = imutils.grab_contours(cnts)

        # print(cnts)

        questionCnts = []

        for c in cnts:
        ar = cv2.contourArea(c)
        cv2.drawContours(thresh, c, -1,(255,0,0),3)
        if ar>=2800 and ar<= 2900:
        questionCnts.append(c)
        # if h >= 42 or h <= 44 and w>=56 or w <= 59 and ar>=1.4 and ar<=1.5:
        # questionCnts.append(c)

        # print(len(cnts))
        print(len(questionCnts))

        questionCnts = contours.sort_contours(questionCnts, method="top-to-bottom")
        [0]
        # print(questionCnts)

        correct = 0

        for (q,i) in enumerate(np.arange(0, len(questionCnts), 4)):
        cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
        bubbled = None
        # print(cnts)

        for (j, c) in enumerate(cnts):
        mask = np.zeros(thresh.shape, dtype="uint8")
        print(mask)
        cv2.drawContours(mask, [c], -1, (255,0,0), 1)

        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 = 0

        if k == bubbled[1]:
        color = (0, 255, 0)
        correct += 1
        print("correct", correct)

        cv2.drawContours(im, [cnts[k]], -1, color, 3)


        # grab the test taker
        score = (correct / 13.0) * 100
        print("[INFO] score: :.2f%".format(score))
        cv2.putText(im, ":.2f%".format(score), (10, 30),
        cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
        # cv2.imshow("Original", image)
        cv2.imshow("Exam", im)

        cv2.waitKey(0)






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 6:40









        Junaid Bin TariqJunaid Bin Tariq

        11 bronze badge




        11 bronze badge





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55335560%2fhow-to-read-a-bubble-sheet-using-cv2-in-python-im-facing-some-issues-reading-c%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

            은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현