简体   繁体   English

OpenCV Python:如何将图像叠加到另一个图像的中心

[英]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调整大小的Img

blankImg空白图片

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.您计算调整后图像左上角的 x 和 y 偏移量,当调整后的图像在背景图像中居中时。 Then use numpy indexing to place the resized image in the center of the background.然后使用 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)


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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM