您当前的位置: 首页 >  Python

Xavier Jiezou

暂无认证

  • 0浏览

    0关注

    394博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

【Python】图像反转/反色的三种方法(pillow)

Xavier Jiezou 发布时间:2022-04-11 16:40:05 ,浏览量:0

cover

引言

图像反转(反色)是将图像的灰度值反转,若图像灰度级为 256,则新图的灰度值为 255 减去原图的灰度值。本文介绍了使用 Python 的 pillow 库进行图像反转(反色)的三种方法。

安装
pip install pillow
方法 方法 1🙂

使用 point() 方法对图像所有像素值进行运算,并返回结果。

from PIL import Image


def invert_color(fname):
    im = Image.open(fname)
    im_inverted = im.point(lambda _: 255-_)
    im_inverted.save(fname.replace('.', '_inverted.'))
    return im_inverted


if __name__ == '__main__':
    invert_color('test.jpg')
方法 2😁

使用嵌套 for 循环遍历图像的每个像素点,并进行取反操作。

from PIL import Image


def invert_color(fname):
    im = Image.open(fname)
    px = im.load()
    w, h = im.size
    for i in range(w):
        for j in range(h):
            if type(px[i, j]) == int:
                px[i, j] = 255-px[i, j]
            elif len(px[i, j]) == 3:
                px[i, j] = tuple([255-i for i in px[i, j]])
            elif len(px[i, j]) == 4:
                px[i, j] = tuple([255-i for i in px[i, j][:3]]+[px[i, j][-1]])
            else:
                pass
    im.save(fname.replace('.', '_inverted.'))
    return im


if __name__ == '__main__':
    invert_color('test.jpg')
方法 3😊

直接使用 ImageChops 中定义的反转函数进行图像颜色反转。

from PIL import Image, ImageChops


def invert_color(fname):
    im = Image.open(fname)
    im_inverted = ImageChops.invert(im)
    im_inverted.save(fname.replace('.', '_inverted.'))
    return im_inverted


if __name__ == '__main__':
    invert_color('test.jpg')
实验 原图通道原图反色13 参考
  • PIL.Image.Image.point
  • PIL.ImageChops.invert
  • PIL.Image.Image.load
  • 图像二值化处理
  • python 图像处理 Pillow 学习笔记
插画

在这里插入图片描述

【画师】森倉円 【P站ID】78693898
关注
打赏
1661408149
查看更多评论
立即登录/注册

微信扫码登录

0.0504s