如何从一张图像的 Y 通道和另一张图像的 U、V 通道创建新图像?

How to create a new image from the Y channel of 1 image, and the U,V channels of another image?

我有两张图片,contentgenerated。我想用 generated 的 Y 通道和 content 的 U 和 V 通道创建一个新图像。使用 PIL,我认为我应该能够使用 .convert('YCbCr') 将我的 RGB 输入图像转换为 YUV。然后在创建新图像后,我可以使用 .convert('RGB') 将其转换为 RGB。

图片以RGB格式进入下面的函数:

def original_colors(content, generated):
    generated_y = generated.convert('YCbCr')
    content_uv = content_uv.convert('YCbCr')
    # Combine Y from generated_y with U and V from content_uv
    # and convert the resulting output back to RGB. 
    return output

将通道组合成新图像的 best/most 有效方法是什么?


这是我采用的解决方案:

# Combine the Y channel of the generated image and the UV/CbCr channels of the
# content image to perform color-independent style transfer.
def original_colors(content, generated):
    content_channels = list(content.convert('YCbCr').split())
    generated_channels = list(generated.convert('YCbCr').split())
    content_channels[0] = generated_channels[0]
    return Image.merge('YCbCr', content_channels).convert('RGB') 

如果alpha_composite()函数没有执行您想要的操作,那么您可以将图像加载到数据数组中,并使用切片替换数组的相关部分。以下似乎使用两个图像工作:

from PIL import Image
import numpy

# open images and make the same size
image1 = Image.open("image1.jpg").resize((256, 256))
image2 = Image.open("image2.jpg").resize((256, 256))

# convert tp YCbCr
image1_y = image1.convert('YCbCr')
image2_y = image2.convert('YCbCr')

# load image data into arrays
image1_y_array = numpy.array(image1_y)
image2_y_array = numpy.array(image2_y)

# show shape and size of arrays
print (image1_y_array.shape)
print (image2_y_array.shape)

#print (image1_y_array[:,:,0])    # uncomment to see actual data
#print (image2_y_array[:,:,0])    # uncomment to see actual data

# replace image 1 Y channel with image 2 Y channel
# assume 1st [0] channel is the Y
image1_y_array[:,:,0] = image2_y_array[:,:,0]

# create new image from the updated array data
new_image1_y = Image.fromarray(image1_y_array)

# and show the result
new_image1_y.show()

# can now convert new_image1_y back to jpeg, etc.

当图像数据加载到数组中时,可以看到数组形状输出的 3 个数据通道:

(256, 256, 3)
(256, 256, 3)

我假定 0 索引通道是 Y 通道,如果不是,则根据需要将幻数 0 替换为 1 或 2。

注意,显然图像应该是相同大小的。希望对您有所帮助。

编辑:

不使用 numpy 也可以做同样的事情:

from PIL import Image

# open images and make the same size
image1 = Image.open("image1.jpg").resize((256, 256))
image2 = Image.open("image2.jpg").resize((256, 256))

# convert tp YCbCr
image1_y = image1.convert('YCbCr')
image2_y = image2.convert('YCbCr')

# split image data
image1_y_data = image1_y.split()
image2_y_data = image2_y.split()

# replace image 1 Y channel with image 2 Y channel
# assume 1st [0] channel is the Y
image1_y_data_list = list(image1_y_data)
image2_y_data_list = list(image2_y_data)

image1_y_data_list[0] = image2_y_data_list[0]

# create new image from the updated data
new_image1_y = Image.merge('YCbCr', image1_y_data_list)

# and show the result
new_image1_y.show()

# can now convert new_image1_y back to jpeg, etc.