在这种情况下,我想创建一组随机的小jpg-大小在50字节至8k之间的任何位置-jpeg的实际视觉内容无关紧要,只要它们有效即可。我需要生成一千个左右,并且它们都必须唯一-即使它们只有一个像素不同。我可以在其中写一个jpeg标头/页脚和一些随机字节吗?我无法使用网络上现有的照片或照片集。
第二个问题是,该程序的每次运行图像集都必须不同。
我更喜欢在python中这样做,因为包装脚本在python中。
我一直在寻找从头开始生成jpg的python代码,但没有找到任何东西,因此指向库的指针也一样。
如果图像只能是随机噪声,则可以使用numpy.random
生成数组,并使用PIL的Image.save
保存它们。
此示例可能会扩展,包括避免(非常不可能)重复模式的方法:
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)
为了获得jpeg图像,必须满足以下条件:
此外,在不需要纯噪声的情况下,可以使用除纯随机性之外的其他方法来生成图像。
如果您不关心文件的内容,则可以通过以下方式使用枕头(PIL.Image.new
[0])创建有效的JPEG:
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
//编辑:我以为OP想要生成有效的图像并且不关心它们的内容(这就是为什么我建议使用单色图像的原因)。这是一个生成具有随机像素的有效图像的函数,此外,它还会向生成的图像写入随机字符串。唯一的依赖关系是Pillow,其他所有东西都是纯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()
如果您正在寻找一种方法,而无需使用numpy,这对我来说是有效的
((Python 3.6为字节,您仍然需要枕头)
import random as r
from PIL import Image
dat = bytes([r.randint(1,3) for x in range(4500000)])
i = Image.frombytes('1', (200,200), dat)