Create set of random JPGs

If you do not care about the content of a file, you can create valid JPEG using Pillow (PIL.Image.new [0]) this way:

from PIL import Image

width = height = 128
valid_solid_color_jpeg = Image.new(mode='RGB', size=(width, height), color='red')
valid_solid_color_jpeg.save('red_image.jpg')

[0] https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.new

// EDIT: I thought OP wants to generate valid images and does not care about their content (that's why I suggested solid-color images). Here's a function that generates valid images with random pixels and as a bonus writes random string to the generated image. The only dependency is Pillow, everything else is pure Python.

import random
import uuid

from PIL import Image, ImageDraw    


def generate_random_image(width=128, height=128):
    rand_pixels = [random.randint(0, 255) for _ in range(width * height * 3)]
    rand_pixels_as_bytes = bytes(rand_pixels)
    text_and_filename = str(uuid.uuid4())

    random_image = Image.frombytes('RGB', (width, height), rand_pixels_as_bytes)

    draw_image = ImageDraw.Draw(random_image)
    draw_image.text(xy=(0, 0), text=text_and_filename, fill=(255, 255, 255))
    random_image.save("{file_name}.jpg".format(file_name=text_and_filename))

# Generate 42 random images: 
for _ in range(42):
    generate_random_image()

If the images can be only random noise, so you could generate an array using numpy.random and save them using PIL's Image.save.

This example might be expanded, including ways to avoid a (very unlikely) repetition of patterns:

import numpy
from PIL import Image

for n in range(10):
    a = numpy.random.rand(30,30,3) * 255
    im_out = Image.fromarray(a.astype('uint8')).convert('RGB')
    im_out.save('out%000d.jpg' % n)

These conditions must be met in order to get jpeg images:

  1. The array needs to be shaped (m, n, 3) - three colors, R G and B;
  2. Each element (each color of each pixel) has to be a byte integer (uint, or unsigned integer with 8 bits), ranging from 0 to 255.

Additionaly, some other way besides pure randomness might be used in order to generate the images in case you don't want pure noise.

Tags:

Python

Jpeg