python pillow Image
はじめに
今回はdetect_facesのBounding Boxとテキストをpillowに置き換えてみる。
※写真はAIで生成したものらしいです。
準備
先にpillowをインストールする。
pip install pillow
下記のプログラムを用意する。
- detect_faces_pillow.py
from PIL import Image, ImageDraw, ImageFont import boto3, sys, json, os, traceback #detect_facesで顔の分析結果を返す def detect_faces(image): client=boto3.client('rekognition') #写真を読み出して、Byte変換してdetect_faces送信 file = open(image,'rb') response = client.detect_faces(Image={'Bytes':file.read()},Attributes=['ALL']) return response #BoundingBoxを設定する def set_bounding_box(image, bounding_box_data): #画像の高さと幅を取得 imgWidth, imgHeight = image.size draw = ImageDraw.Draw(image) #位置を算出 left = bounding_box_data['Left'] * imgWidth top = bounding_box_data['Top'] * imgHeight width = bounding_box_data['Width'] * imgWidth height = bounding_box_data['Height'] * imgHeight points = ( (left,top), (left + width, top), (left + width, top + height), (left , top + height), (left, top) ) draw.line(points, fill='#00d400', width=2) return #指定箇所にtextを設定する def set_text_image(image, text, pos): draw = ImageDraw.Draw(image) #フォントの設定 font_ttf = "/usr/share/fonts/truetype/fonts-japanese-gothic.ttf" draw.font = ImageFont.truetype(font_ttf, 25) color = (0,255,0) #文字の吐き出し draw.text(pos, text, color) return if __name__ == '__main__': if len(sys.argv) != 3: exit() in_file_name = sys.argv[1] out_file_name = sys.argv[2] try: #顔分析 #jsonが無ければ分析あれば使う json_file_name = in_file_name + '.json' if (os.path.exists(json_file_name) == True): file = open(json_file_name, 'r') response = file.read() response = json.loads(response) else: response = detect_faces(in_file_name) file = open(json_file_name, 'w') file.write(json.dumps(response)) #分析元の画像を読み込み image = Image.open(in_file_name) #画像に分析結果の設定(複数人できるが今回は一人だけ) for faceDetail in response['FaceDetails']: #boundingboxを設定 text = '対象の年齢は'+ str(faceDetail['AgeRange']['Low']) + 'から' + str(faceDetail['AgeRange']['High']) + '歳です。' set_bounding_box(image, faceDetail['BoundingBox']) set_text_image(image, text, (0,0)) break #結果の出力 image.save(out_file_name) except Exception as e: print(e) print(traceback.format_exc())
実行方法
python detect_faces_pillow.py 分析したいファイル.jpg 出力したいファイル名.jpg
- 実行結果
BoundingBoxもちゃんと表示され、テキストも日本語で表示されている。
まとめ
Pillowのほうがフォントがボヤボヤしている気がするけど、線はきれい感じがする。
使いでとしては、簡易なCV2と行った感じなのかな?