1
3

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.

多数の画像を一括でリネイム、リサイズ、拡張子を変更しzip化

Posted at

画像のリネイム・リサイズ・拡張子変更・zip化するクラス

ディレクトリに入っている画像の名前、サイズ、拡張子を一括で変更してzip化までやりたかったのでコードを書いてみた

画像前処理クラス.py
from  PIL import Image
import os
import shutil
import cv2
from pathlib import Path

class IMG():
    def __init__(self,dic):
        """初期化時には画像を置いてるディレクトリのパスをいれる"""
        self.directory=dic
    
    def convert(self,suffix):
        """拡張子を任意の拡張子に変更するメソッド
        引数には.(ドット)を除いた拡張子をいれる"""
        for i in os.listdir(self.directory):
            fp = self.directory + '/' + i 
            img=cv2.imread(fp)
            file_Path=Path(fp)
            cv2.imwrite(self.directory + '/' +file_Path.stem + '.' + suffix,img)
            if file_Path.suffix != '.jpg':
                os.remove(fp)
        return self

    
    def rename(self,new_file):
        """ファイル名を任意をファイル名に変更するメソッド
        引数には変更したいファイル名をいれる"""
        data=os.listdir(self.directory)
        for i, old_name in enumerate(data):
            path = self.directory + '/' + old_name
            # ファイル名の決定
            new_name = new_file + "_{0:03d}.jpg".format(i + 1)
            new_path= self.directory + '/' +new_name
            # ファイル名の変更
            os.rename(path, new_path)
        return self
            
    def resize(self,width,height):
        """ファイルサイズを任意のサイズに変更するメソッド
        引数には幅、高さをいれる"""
        for i in os.listdir(self.directory):
            path= self.directory + '/' + i
            img = cv2.imread(path)
            img_resize = cv2.resize(img,(width, height))
            cv2.imwrite(path,img_resize)
        return self
    
    def make_zip(self,zip_name):
        """ディレクトリの画像をzip化するメソッド
        引数には作成するzipファイル名をいれる"""
        shutil.make_archive(zip_name, 'zip', root_dir = self.directory)

まず画像が置かれているディレクトリ名を引数に入れて初期化・
その後任意のメソッドを実行可能、
その際引数には注意(コード上に引数の説明あり)

実行.py
IMG('画像変換_resize/rename').convert('jpg').rename('test').resize(416,416).make_zip('zip化完了')

zip化メソッドまで実行した際にはカレントディレクトリにzipファイルが存在しているはず

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?