【发布时间】:2020-02-03 11:37:05
【问题描述】:
如何将较小的图片粘贴到另一张图片的中心?两张图片的高度相同,但较小的图片的宽度总是更小。
生成的图像应该是较小的图像,周围有黑条,所以它是方形的。
resizedImg = cv2.resize(img, (newW, 40))
blankImg = np.zeros((40, 40, 1), np.uint8)
【问题讨论】:
如何将较小的图片粘贴到另一张图片的中心?两张图片的高度相同,但较小的图片的宽度总是更小。
生成的图像应该是较小的图像,周围有黑条,所以它是方形的。
resizedImg = cv2.resize(img, (newW, 40))
blankImg = np.zeros((40, 40, 1), np.uint8)
【问题讨论】:
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()
观看此video 以了解有关叠加层的更多信息
【讨论】:
这是一种方法。您计算调整后图像左上角的 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)
【讨论】:
cv2.IMREAD_GRAYSCALE