Python 从列表中打印随机彩色像素的图像
我需要打印一种随机像素的“背景”,但只能从给定列表中选择颜色。 我正在使用此代码打印图像:Python 从列表中打印随机彩色像素的图像,python,python-3.x,matplotlib,Python,Python 3.x,Matplotlib,我需要打印一种随机像素的“背景”,但只能从给定列表中选择颜色。 我正在使用此代码打印图像: import numpy as np import matplotlib.pyplot as plt img = (np.random.standard_normal([28, 28, 3]) * 255).astype(np.uint8) plt.imshow(img) 但是我在实现img“数组”列表中的颜色选择时遇到了困难,无论是十六进制还是RGB表示。 任何解决方案都可以,但不一定在matpl
import numpy as np
import matplotlib.pyplot as plt
img = (np.random.standard_normal([28, 28, 3]) * 255).astype(np.uint8)
plt.imshow(img)
但是我在实现img“数组”列表中的颜色选择时遇到了困难,无论是十六进制还是RGB表示。
任何解决方案都可以,但不一定在matplotlib中。谢谢 您可以从列表中随机选择:
import random
colors = ['#AABBCC', '#FFFF00', '#AA00AA']
random_index = random.randint(0, len(colors)-1)
# then you can access the random chosen color like this:
colors[random_index]
我看不出你在哪里实现了这个列表,而且standard_normal会给你[-1,1]中的值,所以在将它们转换为uint8之后,它们在技术上仍然是随机的,并且在正确的范围内,但是 这就是你要找的吗
import numpy as np
import matplotlib.pyplot as plt
numberOfColors = 10
imgShape = [28,28,3]
colorGenerator = lambda channels : [ 127*(np.random.standard_normal([channels]) + 1.0)]
#generate a list of possible colours
colorList = np.array([colorGenerator[channels] for i in range(numberOfColors)],dtype=np.uint8)
#pick a colour from the list for each pixel
indices = np.random.randint(0,numberOfColors,size=[imgShape[0],imgShape[1]]).astype(np.int)
img = colorList[indices].reshape(imgShape)
plt.imshow(img)
plt.show()
据我所知,您需要预定义的颜色列表:
import numpy as np
import matplotlib.pyplot as plt
import random
colors = [
(1.0, 0.0, 0.0),
(0.0, 1.0, 0.0),
(0.0, 0.0, 1.0),
(1.0, 1.0, 0.0),
]
img = np.zeros(shape=(28, 28, 3))
# print(img)
for i in range(28):
for j in range(28):
img[i, j] = random.choice(colors)
plt.imshow(img)
正是我需要的。谢谢