Grim Reaper
Grim Reaper

Reputation: 600

Centering an image using OpenCV and Python

Our program collects a series of images like the one shown:

Character

Now I need to center the 'H' to the center of a 50x50 image (so that it may be fed to a ML algorithm), how do I proceed?

EDIT: All the input data would be similar to the image given and would be in gray scale.

Upvotes: 0

Views: 5328

Answers (2)

samocooper
samocooper

Reputation: 82

You can also use Scikit image to find the image's centre of mass (or you're own function) and then translate the image using padding? A basic way of doing this in Python would be:

im = numpy.zeros((20, 20))
im[2:6, 2:14] = 1


# Determine Centre of Mass

com = ndimage.measurements.center_of_mass(im)

print(com)

# Translation distances in x and y axis

x_trans = int(im.shape[0]//2-com[0])
y_trans = int(im.shape[1]//2-com[1])

# Pad and remove pixels from image to perform translation

if x_trans > 0:
    im2 = numpy.pad(im, ((x_trans, 0), (0, 0)), mode='constant')
    im2 = im2[:im.shape[0]-x_trans, :]
else:
    im2 = numpy.pad(im, ((0, -x_trans), (0, 0)), mode='constant')
    im2 = im2[-x_trans:, :]

if y_trans > 0:
    im3 = numpy.pad(im2, ((0, 0), (y_trans, 0)), mode='constant')
    im3 = im3[:, :im.shape[0]-y_trans]

else:
    im3 = numpy.pad(im2, ((0, 0), (0, -y_trans)), mode='constant')
    im3 = im3[:, -y_trans:]


print(ndimage.measurements.center_of_mass(im3))

Upvotes: 0

JonLuca
JonLuca

Reputation: 919

Are they all going to be letters (or even H's)?

There are a few ways to approach this. The fastest (but most naive) way would be to find the left-most and right-most black pixels, and then center at the halfway point. Then do the same vertical. Basically create a bounding box to your image, where you filter on anything that isn't #FFFFFF

Again, depends on the data though.

Upvotes: 3

Related Questions