gpt4 book ai didi

python - 如何使用 OpenCV 和 Python 制作矩形图像的正方形?

转载 作者:太空宇宙 更新时间:2023-11-03 21:13:31 26 4
gpt4 key购买 nike

我有各种各样的矩形图像。我需要将它们修改为统一的方形(不同大小可以)。

为此,我必须将它叠加在较大的方形之上。背景为黑色。

当我需要分层 2 图像时,我想到了这一点:

import cv2
import numpy as np
if 1:
img = cv2.imread(in_img)
#get size
height, width, channels = img.shape
print (in_img,height, width, channels)
# Create a black image
x = height if height > width else width
y = height if height > width else width
square= np.zeros((x,y,3), np.uint8)
cv2.imshow("original", img)
cv2.imshow("black square", square)
cv2.waitKey(0)

如何将它们堆叠在一起,使原始图像在黑色形状的顶部垂直和水平居中?

最佳答案

我想通了。你需要“广播成型”:

square[(y-height)/2:y-(y-height)/2, (x-width)/2:x-(x-width)/2] = img

最终草案:

import cv2
import numpy as np
if 1:
img = cv2.imread(in_img)
#get size
height, width, channels = img.shape
print (in_img,height, width, channels)
# Create a black image
x = height if height > width else width
y = height if height > width else width
square= np.zeros((x,y,3), np.uint8)
#
#This does the job
#
square[int((y-height)/2):int(y-(y-height)/2), int((x-width)/2):int(x-(x-width)/2)] = img
cv2.imwrite(out_img,square)
cv2.imshow("original", img)
cv2.imshow("black square", square)
cv2.waitKey(0)

关于python - 如何使用 OpenCV 和 Python 制作矩形图像的正方形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45646201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com