2021年11月3日水曜日

【Pillow】画像の新規作成(Image.new)

画像処理ライブラリPillowで画像を新規に作成するにはImage.newを使う。

Pillow(PIL) を使うためにはインポートが必要。 PIL.Imageモジュールは通常以下の形式でインポートされる。

from PIL import Image


1. Image.newの書式

Image.new の書式は以下の通り。

PIL.Image.new(mode, size, color=0)
引数 意味
mode 画像のチャンネル・階調を指定
size 画像サイズ。(幅、高さ)をピクセル数のタプルで指定
color 画像の色。デフォルトは黒(=0)。バンド数の整数もしくは浮動小数点数で指定。RGBモードの場合カラーコードも使用可


modeは画像の形式および色深度(ピクセル毎のビット数)を決める。色深度が1ビットの場合0-1の範囲、8ビットの場合0-255の範囲となる。
主要なmodeは以下

1 1-bit pixels, black and white, stored with one pixel per byte
L 8-bit pixels, black and white
P 8-bit pixels, mapped to any other mode using a color palette
RGB 3x8-bit pixels, true color
RGBA 4x8-bit pixels, true color with transparency mask
CMYK 4x8-bit pixels, color separation
YCbCr 3x8-bit pixels, color video format


2. 使用例

mode=L(8ビットモノトーン)、画像サイズ幅300x高さ200、ピクセルの値190の場合

from PIL import Image

im = Image.new('L', (300, 200), 190)
im.save('image.png')

実行結果





mode=RGB(8ビットRGBカラー)、画像サイズ幅100x高さ250、ピクセルの値RGB = (200, 50, 50)の場合

from PIL import Image

im = Image.new('RGB', (100, 250), (200, 50, 50))
im.save('image.png')

実行結果





3. リファレンス

Pillow (PIL Fork) > Image Module > Constructing images > PIL.Image.new(mode, size, color=0)
Pillow (PIL Fork) > Docs > Handbook > Concepts > Modes

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

0 件のコメント:

コメントを投稿