45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
import numpy as np
|
|
from PIL import Image, ImageEnhance
|
|
import io
|
|
|
|
def pixelate(img_name: str,
|
|
saturation: float = 1.25,
|
|
contrast: float = 1.2,
|
|
n_colors: int = 10,
|
|
superpixel_size: int = 10):
|
|
"""
|
|
See: https://github.com/ferretj/pixelate
|
|
"""
|
|
|
|
img = Image.open(img_name)
|
|
img_size = img.size
|
|
|
|
# boost saturation of image
|
|
sat_booster = ImageEnhance.Color(img)
|
|
img = sat_booster.enhance(saturation)
|
|
|
|
# increase contrast of image
|
|
contr_booster = ImageEnhance.Contrast(img)
|
|
img = contr_booster.enhance(contrast)
|
|
|
|
# reduce the number of colors used in picture
|
|
img = img.convert('P', palette=Image.ADAPTIVE, colors=n_colors)
|
|
# reduce image size
|
|
reduced_size = (img_size[0] // superpixel_size, img_size[1] // superpixel_size)
|
|
img = img.resize(reduced_size, Image.BICUBIC)
|
|
|
|
# resize to original shape to give pixelated look
|
|
img = img.resize(img_size, Image.BICUBIC)
|
|
|
|
return img
|
|
|
|
|
|
def img2byte(img:Image):
|
|
imgByteArr = io.BytesIO()
|
|
img.save(imgByteArr, format="PNG")
|
|
imgByteArr = imgByteArr.getvalue()
|
|
return imgByteArr
|
|
|
|
if __name__ == '__main__':
|
|
img = pixelate("img.jpg")
|
|
img.save("out.png") |