holmeshoo/beans_sorting
0
1from PIL import Image2import os3import sys4 5 6def findMaximumImg(directory):7 # 初期値を負の無限大に設定8 max_pixels = float('-inf')9 max_height = float('-inf')10 max_width = float('-inf')11 12 # result リストの初期値として、[0, 0, 0, None] を 3 回繰り返す13 result = [0, 0, 0, None] * 314 15 # 指定ディレクトリとそのサブディレクトリを再帰的に探索16 for root, dirs, files in os.walk(directory):17 for filename in files:18 # 対応する画像ファイルかどうかを確認19 if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):20 image_path = os.path.join(root, filename)21 22 # 画像を開いてサイズを取得23 with Image.open(image_path) as img:24 width, height = img.size25 pixels = width * height26 27 # 最大の高さを更新28 if height > max_height:29 max_height = height30 result[0] = [height, width, pixels, image_path]31 # 最大の幅を更新32 if width > max_width:33 max_width = width34 result[1] = [height, width, pixels, image_path]35 # 最大の画素数を更新36 if pixels > max_pixels:37 max_pixels = pixels38 result[2] = [height, width, pixels, image_path]39 40 return result41 42 43def findMinimamImg(directory):44 # 初期値を無限大に設定45 min_pixels = float('inf')46 min_height = float('inf')47 min_width = float('inf')48 49 # result リストの初期値として、[0, 0, 0, None] を 3 回繰り返す50 result = [0, 0, 0, None] * 351 52 # 指定ディレクトリとそのサブディレクトリを再帰的に探索53 for root, dirs, files in os.walk(directory):54 for filename in files:55 # 対応する画像ファイルかどうかを確認56 if filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):57 image_path = os.path.join(root, filename)58 59 # 画像を開いてサイズを取得60 with Image.open(image_path) as img:61 width, height = img.size62 pixels = width * height63 64 # 最小の高さを更新65 if height < min_height:66 min_height = height67 result[0] = [height, width, pixels, image_path]68 # 最小の幅を更新69 if width < min_width:70 min_width = width71 result[1] = [height, width, pixels, image_path]72 # 最小の画素数を更新73 if pixels < min_pixels:74 min_pixels = pixels75 result[2] = [height, width, pixels, image_path]76 77 return result78 79 80if __name__ == "__main__":81 args = sys.argv82 83 # コマンドライン引数から指定したディレクトリのパスを取得84 directory_path = args[1]85 86 # 最小の画素数を持つ画像の情報を取得87 max_rseult = findMaximumImg(directory_path)88 min_result = findMinimamImg(directory_path)89 90 # 結果を表示91 print(f'Maximum Height: {max_rseult[0]}\nMaximum Width: {max_rseult[1]}\nMaximum Pixels: {max_rseult[2]}\n')92 print(f'Minimum Height: {min_result[0]}\nMinimum Width: {min_result[1]}\nMinimum Pixels: {min_result[2]}')93# exampl:python .\find_min_max_img.py .\beens\red\data\94 