简体   繁体   English

如何在 PIL 中随机生成 500x500 像素的图像,但我可以选择什么颜色?

[英]How to generate a 500x500 pixel image in PIL with random place but i can choose what colors?

So for example I want the colors red, blue, and yellow in the 500x500 and the placement has to be random.因此,例如,我想要 500x500 中的红色、蓝色和黄色,并且位置必须是随机的。 I was looking at some posts and the documentation but couldn't really find it.我正在查看一些帖子和文档,但实际上找不到。 With the image I'm going to convert it to a pygame surface using "pygame.image.fromstring".有了图像,我将使用“pygame.image.fromstring”将其转换为 pygame 表面。

it should be something like this but in 500x500 and the colors only should be randomized with red, blue and yellow, instead of all those random colors enter image description here它应该是这样的,但在 500x500 中,颜色只能随机使用红色、蓝色和黄色,而不是所有这些随机颜色在此处输入图像描述

Thank You!谢谢你!

You can iterate over each pixel in your image and replace it with randomly selected value from the list of provided colors:您可以遍历图像中的每个像素,并将其替换为从提供的颜色列表中随机选择的值:

import random
from PIL import Image


def create_image(colors):
    image = Image.new('RGB', (500, 500))
    for x in range(image.width):
        for y in range(image.height):
            image.putpixel((x, y), random.choice(colors))
    image.save('image.png')


create_image(colors=[(255, 0, 0), (0, 0, 255), (255, 255, 0)])

Output:输出:

红色、蓝色和黄色

If you only want three colours (or any other number under 256) you should consider using a palette image where, rather than storing three bytes for the RGB values of each pixel, you store a single byte which is the index into a palette (or table) of 256 colours.如果您只想要三种颜色(或 256 以下的任何其他数字),您应该考虑使用调色板图像,而不是为每个像素的 RGB 值存储三个字节,而是存储一个字节,它是调色板的索引(或表)的 256 种颜色。 It is much more efficient.它效率更高。 See discussion here .请参阅此处的讨论。

So, the fastest and most memory efficient way is to initialise your image to random integers in range 0..2 and then push in a palette of your 3 colours:因此,最快和最节省内存的方法是将图像初始化为 0..2 范围内的随机整数,然后推入 3 种颜色的调色板:

import numpy as np
from PIL import Image

# Make a Numpy array 500x500 of random integers 0, 1 or 2
na = np.random.randint(0, 3, (500,500), np.uint8)

# Convert to PIL Image
im = Image.fromarray(na)

# Push in 3-entry palette with red, blue and yellow:
im.putpalette([255,0,0, 0,0,255, 255,255,0])

# Save
im.save('result.png')

在此处输入图像描述


That takes 1ms on my Mac compared to 180ms for iterating over the pixels and choosing one of 3 RGB colours for each, and creates a 50kB palletised output file rather than the 120kB RGB output file you get with the other method.这在我的 Mac 上需要 1 毫秒,而在像素上迭代并为每种颜色选择 3 种 RGB 颜色中的一种需要 180 毫秒,并创建一个 50kB 托盘化输出文件,而不是使用其他方法获得的 120kB RGB 输出文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM