psuresh
psuresh

Reputation: 584

Create animated gif from static image

I have a set of RGB values. I need to put them in individual pixels. I did this with PIL, but I need to plot pixel one by one and look at the progress instead of getting the final image.

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

Upvotes: 3

Views: 603

Answers (1)

Alderven
Alderven

Reputation: 8270

You can generate something like this:

enter image description here

with following code (thx @Mark Setchell for numpy hint):

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)

Or this:

enter image description here

with following code:

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)

Upvotes: 2

Related Questions