【问题标题】:creating an image from two separate arrays从两个单独的数组创建图像
【发布时间】:2020-02-23 14:45:47
【问题描述】:

我有一个形状为(2, 6, 4) 的输出数组,它将代表一个图像文件(6x2 像素)

我还有一组[x,y] 坐标和一组[255,255,255] 颜色值用于每个坐标。

如何使用正确索引中的颜色值填充输出数组,而不使用循环遍历每个索引来完成此操作?

这是一个人为的例子:

import numpy as np
from PIL import Image

xy_coordinates = np.array([[0,0], [1,0], [2,0], [3,0], [4,0], [5,0], [0,1], [1,1], [2,1], [3,1], [4,1], [5,1]])
colours = np.array([['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255'], ['255', '255', '255']])

output_array = np.zeros([2, 6, 4], dtype=np.uint8)

# fill output_array with elements from colours array in correct indices
# at a loss :(

output_img = Image.fromarray(output_array)

任何帮助表示赞赏

【问题讨论】:

  • 一个 (2,6,4) 数组肯定代表 4 个 (6,2) 的图像?或者图像是 4 通道 RGBA 还是 CMYK?
  • 对不起,我应该提到,是的,它是一个 4 通道 RGBA
  • 因此,当您的坐标覆盖每个像素时,您的图像将在 A 通道中到处都是白色且为零。那么为什么不直接做呢?
  • 这是一个好点,但白色只是作为一个例子,实物有很多不同颜色的像素

标签: python arrays numpy colors python-imaging-library


【解决方案1】:

我想这就是你想要的:

import numpy as np

# Create empty black output image
RGB = np.zeros((2, 6, 3), dtype=np.uint8)

# Coordinates of pixels to change
xy_coordinates = np.array([[0,0], [1,1], [0,4], [1,5]])

# Colours to change them to: Red, Green, Blue Yellow
colours = np.array([['255', '0', '0'], ['0', '255', '0'], ['0', '0', '255'], ['255', '255', '0']])

# Do all the entries
for i in range(len(colours)):
    RGB[xy_coordinates[i][0],xy_coordinates[i][1]] = colours[i]

如果你想要一个 alpha 通道,你可以在之后轻松添加它:

A = np.zeros((2,6),np.uint8)
RGBA = np.dstack((RGB,A))

我相信这相当于整个 for 循环,但我不太确定自己:

out[xy_coordinates[:,0],xy_coordinates[:,1]] = colours[:]

也许比我更聪明的人,即@divakar 或其他数千人,可以发表评论/澄清吗?

【讨论】:

  • 我认为你的坐标是另一个顺序,所以你可能需要RGB[xy_coordinates[i][1],xy_coordinates[i][0]] = colours[i]
  • 谢谢马克。 output_array[xy_coordinates[:,1], xy_coordinates[:,0]] = colours[:] 是我需要的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
  • 2021-08-30
  • 1970-01-01
相关资源
最近更新 更多