如何用白色窗口替换图像的一部分?

时间:2018-05-28 06:23:19

标签: python image-processing

我将RGB图像作为Python中的输入,它显然转换为2D numpy数组。我想通过使一个窗口/部分图像完全变为白色(或者用一个只有255的2D numpy数组替换它)来替换它。

这是我试过的:

img[i:i+r,j:j+c] = (np.ones(shape=(r,c))) * 255

r,c是我的窗口大小(128 * 128),我的输入图像是RGB通道。它抛出一个错误:

ValueError: could not broadcast input array from shape (128,128) into shape (128,3)

注意:我希望我的最终输出图像位于RGB通道中,特定部分由白色窗口替换。我使用的是Python 3.5。

1 个答案:

答案 0 :(得分:0)

你可以这样做:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Numpy array containing 640x480 solid blue image
solidBlueImage=np.zeros([480,640,3],dtype=np.uint8)
solidBlueImage[:]=(0,0,255)

# Make a white window
solidBlueImage[20:460,200:600]=(255,255,255)

# Save as PNG
img=Image.fromarray(solidBlueImage)
img.save("result.png")

enter image description here

基本上,我们使用numpy索引来绘制图像。

或者像这样:

#!/usr/local/bin/python3
import numpy as np
from PIL import Image

# Numpy array containing 640x480 solid blue image
solidBlueImage=np.zeros([480,640,3],dtype=np.uint8)
solidBlueImage[:]=(0,0,255)

# Make a white array
h,w=100,200
white=np.zeros([h,w,3],dtype=np.uint8)
white[:]=(255,255,255)

# Splat white onto blue
np.copyto(solidBlueImage[20:20+h,100:100+w,],white)

# Save as PNG
img=Image.fromarray(solidBlueImage)
img.save("result.png")

enter image description here

基本上,我们使用numpy的copyto()来将一个图像粘贴(或复合或叠加)到另一个图像中。