1
0

More than 1 year has passed since last update.

大量の画像ファイルから一部を切り出す

Posted at

画像ファイルの左上を切り出す必要がありました。
image.png
画像ファイルは数百ありまして、画像編集ソフトでひとつひとつ加工するのは大変です。
ということでプログラムにやらせました。

実行準備

ここではUbuntuで必要なライブラリをインストールします。
Pythonの画像処理ライブラリPILのImageモジュールにあるcropメソッドでもいけそうですが、今回はOpenCVを使ってみます。

インストール
apt install -y libgl1-mesa-dev

pip3 install opencv-python
pip3 install opencv-contrib-python

処理コード

imreadメソッドで画像を読み込むと、画像データを2次元配列で返すので [top:bottom, left:right] のようにスライスすればOKです。

Python
import cv2
import glob

for file in glob.glob('img/*.png'):
	img = cv2.imread(file)
	cv2.imwrite(file, img[0:50, 0:120])

なお、globrecursiveTrueを指定し、ファイルパスに**を含めると、サブディレクトリを再帰的に処理できます。

1
0
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
1
0