Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/310.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Putpixel函数不生成所有像素_Python_Image_Python Imaging Library - Fatal编程技术网

Python Putpixel函数不生成所有像素

Python Putpixel函数不生成所有像素,python,image,python-imaging-library,Python,Image,Python Imaging Library,我的目标是每像素生成一种颜色,以填充整个画布。然而,生成的图像总是变成黑色,只有一个像素改变了颜色,我似乎不知道我做错了什么 import random from PIL import Image canvas = Image.new("RGB", (300,300)) y = random.randint(1, canvas.width) x = random.randint(1, canvas.width) r = random.randint(0,255) g =

我的目标是每像素生成一种颜色,以填充整个画布。然而,生成的图像总是变成黑色,只有一个像素改变了颜色,我似乎不知道我做错了什么

import random
from PIL import Image

canvas = Image.new("RGB", (300,300))

y = random.randint(1, canvas.width)
x = random.randint(1, canvas.width)

r = random.randint(0,255)
g = random.randint(0,255)
b = random.randint(0,255)

rgb = (r,g,b)

for i in range(canvas.width): 
    canvas.putpixel((x,y), (rgb))

canvas.save("test.png", "PNG")

print("Image saved successfully.")

代码的问题在于没有迭代每个像素。我已经修改了您的代码,以迭代每个像素,检查它是否为黑色
(0,0,0)
,然后使用随机生成的
rgb
值在该迭代上放置一个像素。然后,我重新生成3个新的随机数,并将它们放回
rgb
元组,从而使循环中的下一个像素具有不同的
rgb

x
y
的定义是多余的,因为您希望每个像素都有一个随机颜色,但不希望有随机像素,所以我已经删除了它们。我添加了一个声明,
pixels=canvas.load()
,它为像素分配内存,这样您就可以迭代像素并更改每个颜色。如果您想了解更多信息,我严重依赖于类似的stackoverflow问题。这是我的密码:

canvas = Image.new("RGB", (300,300))
pixels = canvas.load()

width, height = canvas.size

for i in range(width): 
    for j in range(height):
        if pixels[i,j] == (0,0,0):
            r = random.randint(0,255)
            g = random.randint(0,255)
            b = random.randint(0,255)
            rgb = (r,g,b)
            canvas.putpixel((i,j), (rgb))
            
canvas.save("test.png", "PNG")

print("Image saved successfully.")
以下是生成的输出:


在任何Python图像处理中,都应该尝试避免使用
for
循环,因为它们速度慢且容易出错

制作随机图像最简单、最快速的方法是使用矢量化Numpy函数,如下所示:

import numpy as np
from PIL import Image

# Create Numpy array 300x300x3 of random uint8
data = np.random.randint(0, 256, (300,300,3), dtype=np.uint8)

# Make into PIL Image
im = Image.fromarray(data)

你说得对,我已经删除了那些任务。很抱歉,因为这是我第一次与PIL合作。