Python, OpenCV, Pillow(PIL)で画像サイズ(幅、高さ)を取得
PythonにはOpenCV, Pillow(PIL)などの画像を扱うライブラリがある。それぞれについて画像サイズ(幅、高さ)を取得する方法を説明する。
OpenCVはshape
、Pillow(PIL)はsize
で画像サイズ(幅、高さ)をタプルで取得できるが、それぞれ順番が異なるので注意。
Pythonでの画像処理については以下の記事も参照。
画像サイズを変更(リサイズ)する方法や、画像サイズ(大きさ)ではなくファイルのサイズ(容量)を取得する方法については以下の記事を参照。
OpenCV: ndarray.shapeで画像サイズ(幅、高さ)を取得
OpenCVで画像ファイルを読み込むと、NumPy配列ndarray
として扱われる。ndarray
の形状を示す属性shape
から画像のサイズ(幅、高さ)を取得できる。
OpenCVに限らず、Pillowで画像ファイルを読み込んでndarray
に変換した場合などのndarray
で表されている画像のサイズはshape
で取得する。
なお、OpenCVでカラー画像を読み込んだ場合、色の並びがBGRになるので要注意。
カラー画像の場合
カラー画像の場合は行(高さ) x 列(幅) x 色(3)
の三次元のndarray
となる。shape
は(行(高さ), 列(幅), 色(3))
のタプルとなる。
import cv2
im = cv2.imread('data/src/lena.jpg')
print(type(im))
# <class 'numpy.ndarray'>
print(im.shape)
print(type(im.shape))
# (225, 400, 3)
# <class 'tuple'>
それぞれの値を変数に代入する場合は以下のようにタプルをアンパックする。
h, w, c = im.shape
print('width: ', w)
print('height: ', h)
print('channel:', c)
# width: 400
# height: 225
# channel: 3
タプルをアンパックする場合、それ以降使わない値は慣例的に_
に代入することもある。例えば、色数(チャンネル数)を使わない場合は以下のようにする。
h, w, _ = im.shape
print('width: ', w)
print('height:', h)
# width: 400
# height: 225
変数に代入せずインデックス(添字)で指定してそのまま使うこともできる。
print('width: ', im.shape[1])
print('height:', im.shape[0])
# width: 400
# height: 225
(幅, 高さ)
のタプルを取得したい場合は、スライスを利用して以下のように書ける。cv2.resize()
などの引数をサイズで指定する場合は(幅, 高さ)
を使う。
print(im.shape[1::-1])
# (400, 225)
スライスについての詳細は以下の記事を参照。
グレースケール(モノクロ)画像の場合
グレースケール(モノクロ)画像の場合は行(高さ) x 列(幅)
の二次元のndarray
となる。shape
は(行(高さ), 列(幅))
のタプルとなる。
import cv2
im_gray = cv2.imread('data/src/lena.jpg', cv2.IMREAD_GRAYSCALE)
print(im_gray.shape)
print(type(im_gray.shape))
# (225, 400)
# <class 'tuple'>
基本的にはカラー画像の場合と同じ。
h, w = im_gray.shape
print('width: ', w)
print('height:', h)
# width: 400
# height: 225
print('width: ', im_gray.shape[1])
print('height:', im_gray.shape[0])
# width: 400
# height: 225
幅と高さを変数に代入したい場合、以下のようにすると画像がカラーでもグレースケールでも対応できる。
h, w = im.shape[0], im.shape[1]
print('width: ', w)
print('height:', h)
# width: 400
# height: 225
(幅, 高さ)
のタプルを取得したい場合は、スライスを利用して以下のように書ける。下の書き方([1::-1]
)であれば画像がカラーでもグレースケールでも対応できる。
print(im_gray.shape[::-1])
print(im_gray.shape[1::-1])
# (400, 225)
# (400, 225)
Pillow(PIL): size, width, heightで画像サイズ(幅、高さ)を取得
Pillow(PIL)で画像を読み込むと得られるPIL.Image
オブジェクトは、属性size
, width
, height
をもつ。
size
は(幅, 高さ)
のタプル。
from PIL import Image
im = Image.open('data/src/lena.jpg')
print(im.size)
print(type(im.size))
# (400, 225)
# <class 'tuple'>
w, h = im.size
print('width: ', w)
print('height:', h)
# width: 400
# height: 225
幅と高さそれぞれを属性width
, height
で取得することもできる。
print('width: ', im.width)
print('height:', im.height)
# width: 400
# height: 225
グレースケール(モノクロ)画像でも同じ。
im_gray = Image.open('data/src/lena.jpg').convert('L')
print(im.size)
print('width: ', im.width)
print('height:', im.height)
# (400, 225)
# width: 400
# height: 225