Ask Your Question
0

How can i sort the contours from left to right and top to bottom?

asked 2017-12-01 05:58:30 -0600

master drew gravatar image

updated 2020-10-23 09:01:18 -0600

Code:

import cv2
import numpy as np

    image = cv2.imread('Letter.png')
    cv2.imshow('orig',image)
    cv2.waitKey(0)

    gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    cv2.imshow('gray',gray)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    ret,thresh = cv2.threshold(gray,127,255,cv2.THRESH_BINARY_INV)
    cv2.imshow('second',thresh)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    kernel = np.ones((5,5), np.uint8)
    img_dilation = cv2.dilate(thresh, kernel, iterations=1)
    cv2.imshow('dilated',img_dilation)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    im2,ctrs, hier = cv2.findContours(img_dilation.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    #sort contours
    sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[1])

    for i, ctr in enumerate(sorted_ctrs):
        # Get bounding box
        x, y, w, h = cv2.boundingRect(ctr)

        # Getting ROI
        roi = image[y:y+h, x:x+w]

        # show ROI
        cv2.imshow('segment no:'+str(i),roi)
        cv2.rectangle(image,(x,y),( x + w, y + h ),(90,0,255),2)
        cv2.waitKey(0)
        cv2.destroyAllWindows()

    cv2.imshow('marked areas',image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    print "Number of Contours %d ->"%len(ctrs)
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2017-12-01 06:07:41 -0600

berak gravatar image

updated 2017-12-01 06:09:34 -0600

you're halfway there already.

#sort contours
sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[1])

so far, it only sorts by y position of the bbox. to sort by x and y you'd use:

sorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0] + cv2.boundingRect(ctr)[1] * image.shape[1] )
# x + y * w

(and yea, it's terribly inefficient)

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2017-12-01 05:57:20 -0600

Seen: 18,014 times

Last updated: May 24 '20