2021年11月13日土曜日

【Pillow】ImageOpsモジュールによる画像のネガポジ反転・ポスタリゼーション・ソラリゼーション

 画像処理ライブラリPillowのPIL.ImageOpsモジュールには様々な画像処理機能が用意されている。その中からImageOps.invertによる画像のネガポジ反転、ImageOps.solarizeによるソラリゼーション処理、ImageOps.posterizeによるポスタリゼーション(減色)処理について説明する。
Pillow(PIL)を使うためにはインポートが必要。PIL.ImageOpsモジュールは通常以下の形式でインポートされる。

from PIL import ImageOps

例に用いる画像'sunflower.jpg'は以下を使用(フリー写真素材ぱくたそより)






1. ネガポジ反転(ImageOps.invert)

ImageOps.invertによりネガポジ反転される。各チャンネルの画素値(0~255)を255から引くことでネガポジ反転する。書式は以下の通り。引数は処理する画像を指定するのみ 。

PIL.ImageOps.invert(image)

ImageOps.invertによるネガポジ反転の例

from PIL import Image, ImageOps

# 元画像の読み出し
im = Image.open('sunflower.jpg')  

# invert処理
im_invert = ImageOps.invert(im)

# ファイルの保存
im_invert.save('sunflower_i.jpg', quality=95)

実行結果





2. ソラリゼーション(ImageOps.solarize)

ImageOps.solarizeにより画像がソラリゼーションされる。ソラリゼーションは設定した輝度以上で画素値をネガポジ反転する処理。1つの画像の中にネガ像とポジ像が混在するような効果を与える。
書式は以下。threshold未満の画素はそのまま、threshold以上の画素はネガポジ反転される。thresholdのデフォルト値は128で省略すると128が適用される。

PIL.ImageOps.solarize(image, threshold=128)

ImageOps.solarizeの例。thresholdは128

from PIL import Image, ImageOps

# 元画像の読み出し
im = Image.open('sunflower.jpg')  

# solarize処理
im_solarize = ImageOps.solarize(im, threshold=128)

# ファイルの保存
im_solarize.save('sunflower_s.jpg', quality=95)

実行結果





3. ポスタリゼーション(ImageOps.posterize)

ImageOps.posterizeによりポスタリゼーション(減色処理)される。書式は以下の通り。imageは処理される画像、bitsは各チャンネルの減色後のビット数で1-8の範囲で指定する。元画像がRGBカラーの場合は各チャンネル8ビット(256値)、グレースケールでは1チャンネル8ビット(256値)に対して減色後のビット数に4を指定すると各チャンネル16値、2を指定すると各チャンネル4値に減色される。

PIL.ImageOps.posterize(image, bits)

RGBカラー画像に対してbitsを2とし各チャンネル4値に減色する場合。元画像の256*256*256=16777216色から4*4*4=64色に減色される。

from PIL import Image, ImageOps

# 元画像の読み出し
im = Image.open('sunflower.jpg')  

# posterize処理
im_posterize = ImageOps.posterize(im, 2)

# ファイルの保存
im_posterize.save('sunflower_p.jpg', quality=95)

実行結果





4. リファレンス

Pillow (PIL Fork) > ImageOps Module > PIL.ImageOps.invert(image)
Pillow (PIL Fork) > ImageOps Module > PIL.ImageOps.solarize(image, threshold=128)
Pillow (PIL Fork) > ImageOps Module > PIL.ImageOps.posterize(image, bits)

使用バージョン:Python 3.8.8 / Pillow 8.2.0

0 件のコメント:

コメントを投稿