import os import glob import imghdr import openpyxl import cv2 import logging import logging.config import yaml import math with open('logger.yaml',mode= 'r') as f: config = yaml.safe_load(f.read()) logging.config.dictConfig(config) logger = logging.getLogger('sampleLogger') logger.info('** START imgpaste **') # 定数設定 INPUT_IMG_DIR = '.\\' # 貼り付ける画像を置いておくルートディレクトリ SHEET_TITLE = 'result' # シート名の設定 RESULT_FILE_NAME = '.\\result.xlsx' # 結果を保存するファイル名 # 変数 max_height = [] # 各行の画像の高さの最大値を保持 def get_file_names(set_dir_name): """ ディレクトリ内のファイル名取得(ファイル名のみの一覧を取得) """ file_names = os.listdir(set_dir_name) temp_full_file_names = [os.path.join(set_dir_name, file_name) for file_name in file_names if os.path.isfile(os.path.join(set_dir_name, file_name))] # ファイルかどうかを判定 return temp_full_file_names def attach_img(target_full_file_names): """ 画像を呼び出して、Excelに貼り付け """ #貼り付ける行 set_row_idx = 1 #1画像当たりの行数単位取得 sample_size_img = cv2.imread(target_full_file_names[0]) height, width = sample_size_img.shape[:2] #サイズ取得 tani = math.ceil(height/25) + 2 #18.75ポイント=20ピクセル + 余白 #行の高さ合わせ(18.75ポイント=20ピクセル) img_files_len = len([x for x in target_full_file_names if imghdr.what(x) != None]) for row_height in range(img_files_len * tani): ws.row_dimensions[row_height].height = 18.75 ws.column_dimensions['A'].width = 30 target_full_file_names.sort() # ファイル名でソート for target_file in target_full_file_names: if imghdr.what(target_file) != None: # 画像ファイルかどうかの判定 img = openpyxl.drawing.image.Image(target_file) logger.info(target_file + 'を貼り付け') #ファイル名を設定 cell_address = ws.cell(row=set_row_idx, column=1).coordinate # セルの行列番号から、そのセルの番地を取得 ws[cell_address] = os.path.splitext(os.path.basename(target_file))[0] #imgを貼り付け cell_address = ws.cell(row=set_row_idx, column=2).coordinate # セルの行列番号から、そのセルの番地を取得 img.anchor = cell_address ws.add_image(img) # シートに画像貼り付け set_row_idx += tani #終了メッセージ cell_address = ws.cell(row=set_row_idx, column=1).coordinate # セルの行列番号から、そのセルの番地を取得 ws[cell_address] = 'END' # ワークブック設定 wb = openpyxl.Workbook() ws = wb.worksheets[0] # 1番目のシートを編集対象にする ws.title = SHEET_TITLE # 1番目のシートに名前を設定 file_lists = get_file_names(INPUT_IMG_DIR) attach_img(file_lists) # 画像貼り付け設定 # ファイルへの書き込み wb.save(RESULT_FILE_NAME) #終了 logger.info('** END imgpaste **')
カテゴリー