前提・実現したいこと
顔認識後の切り取りを勉強しているのですが
数日前は問題なく作動したのですが急にエラーが発生しました。
cv::warpAffineのmatrixが空ということのようですが上手く解決ができません。
参考ブログはhttps://blog.capilano-fw.com/?p=2625です。
■■な機能を実装中に以下のエラーメッセージが発生しました。
発生している問題・エラーメッセージ
error Traceback (most recent call last) <ipython-input-56-48cec48ab2a9> in <module> 2 y_diff = points[45][1] - points[36][1] 3 angle = math.degrees(math.atan2(y_diff, x_diff)) ----> 4 rotated_im = fitting_rotated_image(face_im, angle) <ipython-input-53-34ff161a7c2e> in fitting_rotated_image(img, angle) 11 M[1,2] += int((new_height-height)/2) 12 ---> 13 return cv2.warpAffine(img, M, (new_width, new_height)) error: OpenCV(4.1.1) C:\projects\opencv-python\opencv\modules\imgproc\src\imgwarp.cpp:2594: error: (-215:Assertion failed) src.cols > 0 && src.rows > 0 in function 'cv::warpAffine'
該当のソースコード
python
1import cv2 2import dlib 3import numpy as np 4import math 5predictor_path = r'C:\Users\user\Desktop\Goat\python\shape_predictor_68_face_landmarks.dat' 6detector = dlib.get_frontal_face_detector() 7predictor = dlib.shape_predictor(predictor_path) 8im = cv2.imread(r'C:\Users\user\Pictures\singer\baek_yerin.jpg', cv2.IMREAD_COLOR) 9if im is None: 10 print('no') 11 exit() 12rects = detector(im, 1) 13if len(rects) == 0: 14 print('no') 15 exit() 16 17def fitting_rotated_image(img, angle): 18 height,width = img.shape[:2] 19 center = (int(width/2), int(height/2)) 20 radians = np.deg2rad(angle) 21 M = cv2.getRotationMatrix2D(center, angle, 1.0) 22 23 new_width = int(abs(np.sin(radians)*height) + abs(np.cos(radians)*width)) 24 new_height = int(abs(np.sin(radians)*width) + abs(np.cos(radians)*height)) 25 26 M[0,2] += int((new_width-width)/2) 27 M[1,2] += int((new_height-height)/2) 28 29 return cv2.warpAffine(img, M, (new_width, new_height)) 30 31for index,rect in enumerate(rects): 32 33 # 顔だけ切り出す 34 rectWidth = rect.width() 35 rectHeight = rect.height() 36 rectCenter = rect.center() 37 x_start = rectCenter.x - rectWidth 38 x_end = x_start + rectWidth*2 39 y_start = rectCenter.y - rectHeight 40 y_end = y_start + rectHeight*2 41 face_im = im[y_start:y_end, x_start:x_end] 42 43 # 顔の角度を修正 44 points = [] 45 for point in predictor(im, rect).parts(): 46 points.append([int(point.x), int(point.y)]) 47 x_diff = points[45][0] - points[36][0] 48 y_diff = points[45][1] - points[36][1] 49 angle = math.degrees(math.atan2(y_diff, x_diff)) 50 rotated_im = fitting_rotated_image(face_im, angle) 51 cv2.imwrite('rotated_face_'+ str(index) +'.jpg', rotated_im) 52 53 # 回転後の画像で顔検出して画像保存 54 rotated_rects = detector(rotated_im, 1) 55 if len(rotated_rects) == 0: 56 print('no') 57 continue 58 59 rotated_rect = rotated_rects[0] 60 x_start = rotated_rect.left() 61 x_end = rotated_rect.right() 62 y_start = rotated_rect.top() 63 y_end = rotated_rect.bottom() 64 cropped_im = rotated_im[y_start:y_end, x_start:x_end] 65 cv2.imwrite('face_'+ str(index) +'.jpg', cropped_im)
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。