Skip to content
Advertisement

OpenCV Python: How to overlay an image into the centre of another image

How can I paste a smaller image into the center of another image? Both images have the same height, but the smaller one has a width that is always smaller.

The resulting image should be the smaller image with black bars around it so it is square.

resizedImg = cv2.resize(img, (newW, 40))
blankImg = np.zeros((40, 40, 1), np.uint8)

resizedImg

resizedImg

blankImg

blankImg

Advertisement

Answer

Here is one way. You compute the offsets in x and y for the top left corner of the resized image where it would be when the resized image is centered in the background image. Then use numpy indexing to place the resized image in the center of the background.

import cv2
import numpy as np


# load resized image as grayscale
img = cv2.imread('resized.png', cv2.IMREAD_GRAYSCALE)
h, w = img.shape
print(h,w)

# load background image as grayscale
back = cv2.imread('background.png', cv2.IMREAD_GRAYSCALE)
hh, ww = back.shape
print(hh,ww)

# compute xoff and yoff for placement of upper left corner of resized image   
yoff = round((hh-h)/2)
xoff = round((ww-w)/2)
print(yoff,xoff)

# use numpy indexing to place the resized image in the center of background image
result = back.copy()
result[yoff:yoff+h, xoff:xoff+w] = img

# view result
cv2.imshow('CENTERED', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save resulting centered image
cv2.imwrite('resized_centered.png', result)


User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement