【发布时间】:2018-06-15 00:12:23
【问题描述】:
我有一个形状为 (512, 512, 4) 的 numpy 数组 A 每个元素都是一个元组:(r, g, b, a)。它代表一个 512x512 RGBA 图像。
我有一个形状为 (512, 512, 3) 的 numpy 数组 B 每个元素都是一个元组:(r, g, b)。它代表一个相似的 RGB 图像。
我想将 A 的每个元素中的所有“a”(alpha)值快速复制到 B 中的相应元素中。(基本上是传输 alpha 通道)。
生成的 B 形状将是 (512, 512, 4)。
我怎样才能做到这一点?该算法基于here 布局的快速像素操作技术。
代码:
## . input_image is loaded using PIL/pillow
rgb_image = input_image
print(f"Image: {rgb_image}")
rgb_image_array = np.asarray(rgb_image) # convert to numpy array
print(f"Image Array Shape: {rgb_image_array.shape}")
gray_image = rgb_image.convert("L") # convert to grayscale
print(f"Gray image: {gray_image}")
gray_image_array = np.asarray(gray_image)
print(f"Gray image shape: {gray_image_array.shape}")
out_image_array = np.zeros(rgb_image_array.shape, rgb_image_array.dtype)
print(f"Gray image array shape: {out_image_array.shape}")
rows, cols, items = out_image_array.shape
# create lookup table for each gray value to new rgb value
LUT = []
for i in range(256):
color = gray_to_rgb(i / 256.0, positions, colors)
LUT.append(color)
LUT = np.array(LUT, dtype=np.uint8)
print(f"LUT shape: {LUT.shape}")
# get final output that uses lookup table technique.
# notice that at this point, we don't have the alpha channel
out_image_array = LUT[gray_image_array]
print(f"output image shape: {out_image_array.shape}")
# How do I get the alpha channel back from rgb_image_array into out_image_array
输出:
Image: <PIL.Image.Image image mode=RGBA size=512x512 at 0x7FDEF5F2F438>
Image Array Shape: (512, 512, 4)
Gray image: <PIL.Image.Image image mode=L size=512x512 at 0x7FDEF5C25CF8>
Gray image shape: (512, 512)
Gray image array shape: (512, 512, 4)
LUT shape: (256, 3)
output image shape: (512, 512, 3)
【问题讨论】:
-
请在您的问题中添加一个最小且可验证的示例以及您之前尝试过的代码。
-
@Kasramvd - 谢谢。我不知道如何实现它。我添加了更多解释/示例集。
-
那么,这是一个元组列表吗?最小的样本看起来像这样。
-
您将 Q 标记为
numpy,但您不使用 numpy 数组。那么,numpy 数组解决方案是否可以接受? -
@NilsWerner 我用代码更新了这个问题。感谢您指出。