Detect inclination of lines in Python

1.2k Views Asked by At

Im creating a system that will be able to register people who will have written texts by hand, later I will have to analyze this image and detect if the writing is ascending, descending or straight. With graphology, I will be able to create the person's profile, but I have no ideas on how to analyze that image.

System using Python and Django, i just need to read the image to make this analysis.Does anyone have a suggestion on how to do it?

Example of the inclinations

1

There are 1 best solutions below

2
On

A possible solution is to use the minAreaRect() that give you the angle. Once you have it, just set your thresh to say if the writing is ['Ascending', 'Descending', 'Level']:

write = cv2.imread('your_image.png', cv2.IMREAD_COLOR)
write_gray = cv2.cvtColor(write, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(write_gray, 150, 255, cv2.THRESH_BINARY_INV)
# dilate the write
elem = cv2.getStructuringElement(cv2.MORPH_RECT, (4, 4), (2, 2))
dilat = cv2.dilate(thresh, elem, iterations=1)
contours, hierarchy = cv2.findContours(dilat, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

for cnt in contours:
    if cv2.contourArea(cnt) > 1600: # only keep the writing text
        box = cv2.minAreaRect(cnt)
        (pos, size, angle) = box
        box = cv2.boxPoints(box)
        box = np.int0(box)
        cv2.drawContours(write, [box], 0, (0,255,0), 2)
        angle = angle if size[0] > size[1] else angle + 90
        pos = (cnt[cnt[:, :, 0].argmin()][0][0], cnt[cnt[:, :, 1].argmin()][0][1])
        #print(angle)
        if -2 <= angle <= 2:
            cv2.putText(write, 'Level', pos, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (190, 123, 68), 2)
        elif angle < -2:
            cv2.putText(write, 'Ascending', pos, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (190, 123, 68), 2)
        elif 2 < angle:
            cv2.putText(write, 'Descending', pos, cv2.FONT_HERSHEY_SIMPLEX, 0.7, (190, 123, 68), 2)

cv2.imshow('resultat', write)

You will have something like this: result