Skip to content

Instantly share code, notes, and snippets.

@initbar
Created Mar 30, 2019
Embed
What would you like to do?
from PIL import Image
import pprint
import random
import numpy
class RandomPixelsDist(object):
def __init__(self, width=10, height=10, density=0.8):
self.width = width
self.height = height
self.density = density
self.size = self.width * self.height
self.distribution = []
self.pixels = ''
self.image = None
def view(self, indent=2, width=80):
pp = pprint.PrettyPrinter(indent=indent, width=width)
pp.pprint(self.image)
def stat(self):
try: assert self.image
except AssertionError: return 0
[ self.distribution.append(float(sum(row)) / self.width) for row in self.image ]
return self.distribution
def random(self):
self.image = [[ 1 if (random.random() >= (1 - self.density)) else 0 for l in ([0] * self.width) ] for h in range(self.height) ]
return self.image
def export_as_image(self, filename='exported'):
try: assert self.image
except AssertionError: return False
for row in self.image:
for pixel in row:
if pixel: self.pixels += chr(0) * 3
else: self.pixels += chr(255) * 3
image = Image.frombytes('RGB', (self.width, self.height), self.pixels)
image.save(filename + '.png', 'PNG')
return True
if __name__ == '__main__':
x = RandomPixelsDist(256, 256, 0.75)
x.random()
x.export_as_image('sample')
del x
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment