在numpy中的白色画布上添加png图像

2024-05-02 10:07:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个png图像,必须覆盖在白色画布上。png图像尺寸为200*200。画布尺寸为512*512。你知道吗

#SOURCE IMAGE 
img=cv2.imread("xx.png")
import cv2
import numpy as np
img_1 = np.zeros([512,512,1],dtype=np.uint8)
img_1.fill(255)
# or img[:] = 255
cv2.imshow('Single Channel Window', img_1)
print("image shape: ", img_1.shape)
cv2.waitKey(0)
cv2.destroyAllWindows()

Tags: 图像imageimportnumpysourceimgpng尺寸
2条回答

这里canvas是白色区域,img是您的输入图像。你知道吗

canvas = np.zeros((512,512,3))
canvas.fill(255)
img = cv2.imread("xx.png",cv2.IMREAD_COLOR)

canvas[canvas.shape[0]//2-img.shape[0]//2:canvas.shape[0]//2+img.shape[0]//2,
canvas.shape[1]//2-img.shape[1]//2:canvas.shape[1]//2+img.shape[1]//2] = img

这是一个简单的代码,假设源代码和画布都是正方形和RGB图像。你知道吗

标志cv2.IMREAD\u颜色很重要,因为画布是3个通道。 如果要使用灰度,请在画布中使用1个通道,如果要使用png(包括alpha通道),请相应地使用4个通道。你知道吗

你现在所需要的就是把图像放到白色背景中。由于图像形状是200X200,白色背景形状是512X512,因此图像的白色边距将是(512-200)/2 = 156。所以:

import cv2
import numpy as np

img=cv2.imread("xx.png", 0)
row, col = img.shape  # row = 200, col = 200

img_1 = np.zeros([512,512],dtype=np.uint8)
img_1.fill(255)

margin = (512 - row)//2  
img_1[margin: margin+row, margin: margin+column] =  img

cv2.imshow('Single Channel Window', img_1)
print("image shape: ", img_1.shape)
cv2.waitKey(0)
cv2.destroyAllWindows()

也可以使用^{}用白色像素填充原始图像并获得相同的结果。所以,在这种情况下:

img = cv2.imread('1.png', 0)

margin = (512 - 200)//2   
img_1 = np.pad(img, margin, 'constant', constant_values=255)

相关问题 更多 >