从静态图像创建动画gif

2024-04-24 19:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组RGB值。我需要把它们放在单独的像素上。我用PIL做了这个,但是我需要一个接一个地绘制像素并查看进度,而不是得到最终的图像。你知道吗

from PIL import Image
im = Image.open('suresh-pokharel.jpg')
pixels = im.load()
width, height = im.size

for i in range(width):
    for j in range(height):
        print(pixels[i,j])  # I want to put this pixels in a blank image and see the progress in image

Tags: infrom图像imageforpil绘制range
1条回答
网友
1楼 · 发布于 2024-04-24 19:22:13

您可以生成如下内容:

enter image description here

使用以下代码(thx@Mark Setchell for numpy提示):

import imageio
import numpy as np
from PIL import Image

img = Image.open('suresh-pokharel.jpg')
pixels = img.load()
width, height = img.size
img2 = Image.new('RGB', img.size, color='white')
pixels2 = img2.load()

i = 0
images = []
for y in range(height):
    for x in range(width):
        pixels2[x, y] = pixels[x, y]
        if i % 500 == 0:
            images.append(np.array(img2))
        i += 1

imageio.mimsave('result.gif', images)

或者这个:

enter image description here

代码如下:

import random
import imageio
import numpy as np
from PIL import Image

img = Image.open('suresh-pokharel.jpg')
pixels = img.load()
width, height = img.size
img2 = Image.new('RGB', img.size, color='white')
pixels2 = img2.load()

coord = []
for x in range(width):
    for y in range(height):
        coord.append((x, y))

images = []
while coord:
    x, y = random.choice(coord)
    pixels2[x, y] = pixels[x, y]
    coord.remove((x, y))
    if len(coord) % 500 == 0:
        images.append(np.array(img2))

imageio.mimsave('result.gif', images)

相关问题 更多 >