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:
