def prepareImage(imagePath): """ Prepare images before use it. """ print("> Prepare image "+imagePath + ":") imname = ntpath.basename(imagePath) imname = imname.split(imname.split('.')[-1])[0][0:-1] # 记录图片basename img = cv2.imread( imagePath ) # 加载图片 if needCrop: dlib_img = io.imread(imagePath) img2 = cv2.copyMakeBorder(img,0,0,0,0,cv2.BORDER_REPLICATE) detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor(FLAGS.predictor_path) # 加载 dlib 检测 dets = detector(img, 1) print("> Number of faces detected: {}".format(len(dets))) if len(dets) == 0: print '> Could not detect the face, skipping the image...' + image_path return None if len(dets) > 1: print "> Process only the first detected face!" # 标记第一个人脸 detected_face = dets[0] cv2.rectangle(img2, (detected_face.left(),detected_face.top()), \ (detected_face.right(),detected_face.bottom()), (0,0,255),2) fileout = open(os.path.join(FLAGS.tmp_detect , imname + ".bbox"),"w") fileout.write("%f %f %f %f\n" % (detected_face.left(),detected_face.top(), \ detected_face.right(),detected_face.bottom())) fileout.close() ## If we are using landmarks to crop if useLM: shape = predictor(dlib_img, detected_face) nLM = shape.num_parts fileout = open(os.path.join(FLAGS.tmp_detect, imname + ".pts" ), "w") for i in range(0, nLM): cv2.circle( img2, (shape.part(i).x, shape.part(i).y), 5, (255,0,0)) fileout.write("%f %f\n" % (shape.part(i).x, shape.part(i).y)) fileout.close() img = utils.cropByLM(img, shape, img2) else: print "> cropByFaceDet " img = utils.cropByFaceDet(img, detected_face, img2) cv2.imwrite(os.path.join( FLAGS.tmp_detect, imname+"_detect.png"), img2) img = cv2.resize(img, (trg_size, trg_size)) cv2.imwrite(os.path.join(FLAGS.tmp_ims, imname + '.png'), img) return img
fileout.write("%f %f %f %f\n" % (detected_face.left(),detected_face.top(), \ detected_face.right(),detected_face.bottom())) fileout.close() ## If we are using landmarks to crop if useLM: shape = predictor(dlib_img, detected_face) nLM = shape.num_parts fileout = open("tmp_detect/"+imname+".pts","w") for i in range(0,nLM): cv2.circle(img2, (shape.part(i).x, shape.part(i).y), 5, (255,0,0)) fileout.write("%f %f\n" % (shape.part(i).x, shape.part(i).y)) fileout.close() img = utils.cropByLM(img, shape, img2) else: print "> cropByFaceDet " img = utils.cropByFaceDet(img, detected_face, img2) cv2.imwrite("tmp_detect/"+imname+"_detect.png",img2) img = cv2.resize(img,(trg_size, trg_size)) cv2.imwrite("tmp_ims/" + imname + ".png",img) #####CNN fitting ############################## start_time = time.time() # load net try: caffe.set_mode_gpu() caffe.set_device(GPU_ID) except Exception as ex: print '> Could not setup Caffe in GPU ' +str(GPU_ID) + ' - Error: ' + ex print '> Reverting into CPU mode' caffe.set_mode_cpu()