0

使用Python生成像素画图片

 1 year ago
source link: https://www.biaodianfu.com/pixel-image.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

术→技巧, 研发

使用Python生成像素画图片

钱魏Way · 2022-09-10 · 0 次浏览

家里买了微小积木供小朋友玩,由于自带的说明中仅有几幅图,拼了几个就拼完了,于是打算使用Python做一个像素画图片工具。

piexl.jpg

整体逻辑非常简单:

  • 使用Pillow包读取图片
  • 将图片分割成一个个正方形像素块
  • 获取像素块中出现的最多的颜色,将其作为像素块的颜色。
  • 重新拼接图片。

具体代码如下:

from PIL import Image
import collections
pic = Image.open("image.png").convert("RGB")
width, height = pic.size
block = 10 //设置块大小
board = Image.new("RGB", (width // block * block, height // block * block))
for y in range(0, height, block):
for x in range(0, width, block):
temp = pic.crop((x, y, x + block, y + block))
temp_list = list(temp.getdata())
max_color = collections.Counter(temp_list).most_common()[0][0]
# temp_past = Image.new("RGB", temp.size, max_color) 无边框
temp_past = Image.new("RGB", (temp.size[0] - 1, temp.size[1] - 1), max_color)
board.paste(temp_past, (x, y))
board.show()
from PIL import Image
import collections

pic = Image.open("image.png").convert("RGB")
width, height = pic.size
block = 10 //设置块大小

board = Image.new("RGB", (width // block * block, height // block * block))
for y in range(0, height, block):
    for x in range(0, width, block):
        temp = pic.crop((x, y, x + block, y + block))
        temp_list = list(temp.getdata())
        max_color = collections.Counter(temp_list).most_common()[0][0]
        # temp_past = Image.new("RGB", temp.size, max_color) 无边框
        temp_past = Image.new("RGB", (temp.size[0] - 1, temp.size[1] - 1), max_color)
        board.paste(temp_past, (x, y))
board.show()

具体效果:

hellokitty.jpg
hello-kitty-2.png
pappa-pig.png
pappa-pig-2.png

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK