Reputation:
i tried to use pillow to pixalte an image, i can get the average r ,b ,and g values and have been able to set the image to an average color or pixelate it 1x1, how would i pixelate it by with more pixels, i cant find a code space efficent of soing this, i know that it has smething to do with breaking the image into a grid
from PIL import Image
size = (200, 200)
actual = Image.open('My image')
red = []
blue = []
green = []`enter code here`
og = actual.resize(size)
pop = og.load()
for y in range(40):
for x in range(40):
cow = pop[x, y]
red.append(cow[0])
blue.append(cow[1])
green.append(cow[2])
for y in range(og.size[1]):
for x in range(og.size[0]):
pop[x, y] = (cow[0], cow[1], cow[2])
y = sum(red) // len(red)
z = sum(blue) // len(blue)
t = sum(green) // len(green)
og.show()
Upvotes: 0
Views: 1090
Reputation: 2406
I think the easiest way to do it would be to just use PIL.Image.resize function:
from PIL import Image
im = Image.open('./dumpster/Mario_org.jpg')
org_size = im.size
pixelate_lvl = 8
# scale it down
im = im.resize(
size=(org_size[0] // pixelate_lvl, org_size[1] // pixelate_lvl),
resample=0)
# and scale it up to get pixelate effect
im = im.resize(org_size, resample=0)
Upvotes: 3
Reputation: 411
Here is an example of how you can pixelate with Pillow.
from PIL import Image,ImageStat
size = (200, 200)
actual = Image.open('/path/to/your/image.png')
og = actual.resize(size)
output = Image.new('RGB',(200,200))
tile_width = 5
for i in range(0,200,tile_width):
for j in range(0,200,tile_width):
box = (i,j,i+tile_width,j+tile_width)
region = og.crop(box)
median = ImageStat.Stat(region).median
r = Image.new('RGB',(tile_width,tile_width),tuple(median))
output.paste(r,(i,j))
output.show()
Please note that other methods exist for choosing the color of each tile.
Upvotes: 0