如何将较小的图像粘贴到另一个图像的中心?两张图片的高度相同,但较小的图片的宽度始终较小。
生成的图像应该是较小的图像,周围带有黑条,所以它是正方形的。
resizedImg = cv2.resize(img, (newW, 40))
blankImg = np.zeros((40, 40, 1), np.uint8)
答案 0 :(得分:1)
这是一种方法。您可以为调整大小后的图像的左上角计算x和y中的偏移量,当调整大小后的图像在背景图像中居中时将位于该位置。然后使用numpy索引将调整大小后的图像放置在背景的中心。
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)