0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Python】画像ファイルの解像度取得方法メモ

Posted at

Python で画像ファイル (*.png など) から解像度 (WxH) の情報を抽出する方法として

の使い方,速度のメモ.
画像ファイルはいらすとやの人工知能のキャラクターを使用

バージョン情報:Python 3.7.3, OpenCV 4.5.4.60, Pillow 8.4.0, imagesize 1.3.0

OpenCV

インストール

pip install opencv-python

使い方

import cv2

filename = 'ai_character.png'
img = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
height, width = img.shape[:2]
print(f'Height: {height}, Width: {width}')
# Height: 800, Width: 688

Pillow

インストール

pip install pillow

使い方

from PIL import Image

filename = 'ai_character.png'
img = Image.open(filename)
width, height = img.size
print(f'Height: {height}, Width: {width}')
# Height: 800, Width: 688

imagesize

インストール

pip install imagesize

使い方

import imagesize

filename = 'ai_character.png'
width, height = imagesize.get(filename)
print(f'Height: {height}, Width: {width}')
# Height: 800, Width: 688

手法の比較

1,000 回平均を記録 (MacBook Pro (13-inch, 2017, Two Thunderbolt 3 ports))

OpenCV Pillow imagesize
8.4E-3 [s] 1.3E-4[s] 3.6E-5 [s]

OpenCV は cv2.imread で np.ndarray のデータを読み込む一方,Pillow ではデータに処理が施されるまでデータを読み込まない (https://pillow.readthedocs.io/en/latest/reference/Image.html#PIL.Image.open).
また,imagesize では画像ファイルのヘッダをパースするのみである.
よって,速度は OpenCV < Pillow < imagesize となっている.

参考文献

0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?