'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
blankImg
Solution 1:[1]
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)
Solution 2:[2]
import cv2
import numpy as np
back = cv2.imread('back.png')
overlay = cv2.imread('overlay.png')
h, w = back.shape[:2]
print(h, w)
h1, w1 = overlay.shape[:2]
print(h1, w1)
# let store center coordinate as cx,cy
cx, cy = (h - h1) // 2, (w - w1) // 2
# use numpy indexing to place the resized image in the center of
# background image
back[cy:cy + h1, cx:cx + w1] = overlay
# view result
cv2.imshow('back with overlay', back)
cv2.waitKey(0)
cv2.destroyAllWindows()
watch this video to learn more about overlays
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | fmw42 |
Solution 2 |