def face_detect(file, frame_path, csv_data): name = file.replace('.jpg', '').split('-') log = csv_data.iloc[int(name[0])] x = log[3] y = log[4] img = cv2.imread('%s/%s' % (frame_path, file)) img_ = Image.open('%s/%s' % (frame_path, file)) x = img.shape[1] * x y = img.shape[0] * y faces, landmarks = detector.detect_faces(img_) # check if detected faces if len(faces) == 0: # print('no face detect: ' + file) return # no face faces[0][2] = faces[0][2] - faces[0][0] faces[0][3] = faces[0][3] - faces[0][1] bounding_box = bounding_box_check(faces, x, y) if bounding_box is None: # print('face is not related to given coord: ' + file) return # print(file, " ", bounding_box) # print(file, " ", x, y) crop_img = img[bounding_box[1]:bounding_box[1] + bounding_box[3], bounding_box[0]:bounding_box[0] + bounding_box[2]] crop_img = cv2.resize(crop_img, (160, 160)) cv2.imwrite('%s/frame_' % output_dir + name[0] + '_' + name[1] + '.jpg', crop_img)
def predict(): files = request.files img_left = Image.open(files.get('imgLeft')).convert('RGB') img_right = Image.open(files.get('imgRight')).convert('RGB') bbox_left, _ = detect_faces(img_left) bbox_right, _ = detect_faces(img_right) if bbox_left.shape[0] > 0: a, b, c, d, _ = bbox_left[0] img_left = img_left.crop((a, b, c, d)) if bbox_right.shape[0] > 0: a, b, c, d, _ = bbox_right[0] img_right = img_right.crop((a, b, c, d)) distance, similar = is_same(img_left, img_right, THRESHOLD) model_acc = ModelLoaded.acc return jsonify(same=('BERBEDA', 'SAMA')[similar.item()], score=distance.item(), model_acc=model_acc, threshold=THRESHOLD)
def fetch_faces(image, return_landmarks=False): # standarize detector input from cv2 image to PIL Image if isinstance(image, (np.ndarray, np.generic)): image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) image = Image.fromarray(image) # for some reason, detector randomly throws an error try: bboxes, landmarks = detect_faces(image) except ValueError: bboxes, landmarks = [], [] # postprocess bounding bboxes if len(bboxes) > 0: scores = bboxes[:, -1] bboxes = bboxes[:, :-1].astype("int") else: scores = [] return ([bboxes, scores], landmarks) if return_landmarks else bboxes, scores
def detect_and_store(path, final_root_dir, new_size): img = Image.open(path) bounding_boxes, landmarks = detect_faces(img) if len(bounding_boxes) == 0: print("No face detected on image", get_dir_and_file(path)) ''' image should only contains one valid person for the corresponding label/person so, we assume that bounding_boxes shape is always (1, 5) ''' for a, b, c, d, _ in bounding_boxes: dst = os.path.join(final_root_dir, path.parent.name) os.makedirs(dst, exist_ok=True) final_name = os.path.join(dst, path.name) try: img.crop((a, b, c, d)).resize((new_size, new_size), Image.BILINEAR).save(final_name) print(get_dir_and_file(path), 'saved to', final_name) except Exception as e: print("Error occured when saving", get_dir_and_file(path)) print("Error: ", str(e))
from torch_mtcnn import detect_faces from PIL import Image from os import listdir from os.path import isfile, join import json import csv with open('configuration.json', 'r') as configfile: config_info=json.load(configfile) print(config_info['input-images-directory']) input_images_path=config_info['input-images-directory'] print(input_images_path) image_files = [f for f in listdir(input_images_path) if isfile(join(input_images_path, f))] cropped_images_path=config_info['cropped-faces-directory'] for file in image_files: image = Image.open(input_images_path+file).convert('RGB') bounding_boxes, landmarks = detect_faces(image) for i in range(len(bounding_boxes)): area = (bounding_boxes[i][0],bounding_boxes[i][1],bounding_boxes[i][2],bounding_boxes[i][3]) t_image=image.crop(area) j=i+1 t_image=t_image.save(cropped_images_path+str(j)+'-'+file)
print(m.keys()) classes = m['classes'] net = eval(args.model.type)(args.model.num_classes) net.load_state_dict(m['model']) net.to(torch.device('cuda')) net.eval() i = 0 while ret: raw = frame i+=1 if i % 2 == 0: continue pil_img = cv2_to_pil(raw) bounding_boxes, landmarks = detect_faces(pil_img) print(bounding_boxes) for bbox in bounding_boxes: x1, y1, x2, y2 = int(bbox[0]), int(bbox[1]), int(bbox[2]), int(bbox[3]) cv2.rectangle(raw, (x1, y1), (x2, y2), (0, 255, 0)) frame = raw[y1: y2, x1: x2, :] cv2.imshow('face', frame) # 模型处理 img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) img = cv2.resize(img, (224, 224))