有没有一种方法可以将三值数组转换为图像? [英] Is there a way to convert a 3-value array into an image?

查看:87
本文介绍了有没有一种方法可以将三值数组转换为图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将随机填充数字(0,1,2)的数组转换为图像,其中每个数字都显示为不同的颜色(如果可能的话,最好由我选择),但是我找不到任何图像做到的方式。

I'm trying to convert an array filled randomly with numbers (0,1,2) to an image where every number is shown as a different color (preferably picked by me if possible), but I can't find any way to do it. Is there someone who knows if it can be done?

我尝试使用PIL,但事实证明我的尝试非常不令人满意。如果有人可以提供帮助,我将不胜感激。

I tried to use PIL but my tries are proving to be very unsatisfactory. I'd really appreciate if someone could help.

我知道如何将其显示为图像,但是我没有不知道如何将其随机化。假设我有一个尺寸为400x500的数组,并且我想使每个单元格都具有三个值之一,可以这样做吗?
(这部分代码的大部分来自注释,不是我写的)

I got how to show it as an image, but I don't know how to randomize it. Let's say I have an array with dimensions 400x500 and I'd like to make every cell have one of the three values, can I do something like this? (most of this part of code is from a comment, it's not written by me)

from PIL import Image 
import numpy as np 

w, h = 500, 400 
a = [255, 0, 0]
b = [0, 255, 0]
c = [0, 0, 255]
data = np.array(np.random.random((a,b,c),(h, w, 3), dtype=np.uint8) 
#I'd like the random.random to take one of the three values ("[255, 0, 0]", "[0,255, 0]", or "[0, 0, 255]") 
img = Image.fromarray(data, 'RGB') 

img.save('my.png') 
img.show() 

有办法吗?

我现在明白了,谢谢大家的帮助!

I got it now, thank you for the help everybody!

推荐答案

您与代码非常接近,只是缺少查找表(LUT)来查找与您的0,1,2数据相对应的颜色:

You were very close with your code, you were just missing a Look Up Table (LUT) to look up the colour corresponding to your 0,1,2 data:

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

# Specify image size, create and fill with random 0, 1, or 2
w, h = 500, 400 
data = np.random.randint(0,3,(h, w), dtype=np.uint8)

# Make LUT (Look Up Table) with your 3 colours
LUT = np.zeros((3,3),dtype=np.uint8)
LUT[0]=[255,0,0]
LUT[1]=[0,255,0]
LUT[2]=[0,0,255]

# Look Up each pixel in the LUT
pixels = LUT[data]

# Convert Numpy array to image, save and display
img = Image.fromarray(pixels) 
img.save('result.png')
img.show() 

这篇关于有没有一种方法可以将三值数组转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆