find center coordinates of each character in word on image opencv python

Viewed 570

I have a word on an image word is written on image using cv2.puttext. and each word's height and width we are getting by cv2.getTextSize. Now i want to print the center coordinate both x-coordinate and y-coordinate of each character of word and save them as text file with the normalized value of image height and width . Please have a look at the code for more clarity . Below code is able to give the center coordinate of 1st character of word but not the second and more characters .

1 Answers

With OpenCV you can find the contours of the letters in your image and then find the centers of those contours; here is an example:

Start with this image:

import cv2
import numpy as np

text = 'test123'
org, font, scale, color, thickness = (25,200), cv2.FONT_HERSHEY_SIMPLEX, 3, 255, 3
img = np.zeros((400,400), np.uint8)
cv2.putText(img, text, org, font, scale, color, thickness, cv2.LINE_AA)

source image

Find the contours:

colors = [(200,0,0), (0,200,0),(0,0,200),(123,200,0),(200,0,123),(0,123,200),(200,0,200)]
img_color = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
contours, _ = cv2.findContours(img, cv2.THRESH_BINARY, cv2.CHAIN_APPROX_SIMPLE)
for contour in contours:
    cv2.drawContours(img_color, [contour], -1, colors[0], 2)
    colors.pop(0)

contours

Find the centers of the contours:

for contour in contours:
    center, _ = cv2.minEnclosingCircle(contour)

centers

Related