【转载】【代码正确排版】Python用61行代码实现图片像素化的示例代码

起因

看到网上的像素图片,感觉蛮有趣的,就打算用python一些PIL类库写一个。

在这里插入图片描述

实现思路

把一张图片分成多个块,每个块的颜色都等于这个色块中颜色最多的颜色,如下图。

在这里插入图片描述

这个图取2×2的像素为块的大小,把快中颜色与每个颜色出现的数量存放到字典里,取最大的颜色,填充整个块。

具体实现


```python
from PIL import Image


def init():
    # 设置每个像素区块的大小

    block_size = 30

    img = Image.open("a.png")

    # 获取图片的宽高

    width, height = img.size

    # 获取像素点对应RGB颜色值,可以改变img_array中的值来改变颜色值

    img_array = img.load()

    # 为了处理最后的区块,加了一次循环

    max_width = width + block_size

    max_height = height + block_size

    for x in range(block_size - 1, max_width, block_size):

        for y in range(block_size - 1, max_height, block_size):

            # 如果是最后一次循环,则x坐标等于width - 1

            if x == max_width - max_width % block_size - 1:
                x = width - 1

            # 如果是最后一次循环,则x坐标等于height - 1

            if y == max_height - max_height % block_size - 1:
                y = height - 1

            # 改变每个区块的颜色值

            change_block(x, y, block_size, img_array)

            y += block_size

        x += block_size

    img.save('output.png')

    img.show()


"""

:param x坐标 x:

:param y坐标 y:

:param 区块大小 black_size:

:param 可操作图片数组 img_array:

"""


def change_block(x, y, black_size, img_array):
    color_dist = {}

    block_pos_list = []

    for pos_x in range(-black_size + 1, 1):

        for pos_y in range(-black_size + 1, 1):
            # todo print(x + pos_x,y + pos_y)

            block_pos_list.append([x + pos_x, y + pos_y])

    for pixel in block_pos_list:

        if not str(img_array[pixel[0], pixel[1]]) in color_dist.keys():

            color_dist[str(img_array[pixel[0], pixel[1]])] = 1

        else:

            color_dist[str(img_array[pixel[0], pixel[1]])] += 1

    # key-->value => value-->key

    new_dict = {v: k for k, v in color_dist.items()}

    max_color = new_dict[max(color_dist.values())]

    # 将区块内所有的颜色值设置为颜色最多的颜色

    for a in block_pos_list:
        img_array[a[0], a[1]] = tuple(list(map(int, max_color[1:len(max_color) - 1].split(","))))


def get_key(dict, value):
    return [k for k, v in dict.items() if v == value]


if __name__ == "__main__":
    init()

效果对比

在这里插入图片描述
在这里插入图片描述
总结

还有很多改进的地方,比如取色值的算法上,应该有更好的解决方法,应该用多进程来实现,这样程序速度会快很多。OvO

参考文章

https://blog.csdn.net/weixin_39768388/article/details/109950186

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值