本文整理汇总了Python中face_recognition.load_image_file方法的典型用法代码示例。如果您正苦于以下问题:Python face_recognition.load_image_file方法的具体用法?Python face_recognition.load_image_file怎么用?Python face_recognition.load_image_file使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类face_recognition
的用法示例。
在下文中一共展示了face_recognition.load_image_file方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: loadKnown
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def loadKnown(self, label):
console.task('Loading known faces')
pa_g = Path('./known')
pathlist = []
for ext in ['.jpg', '.JPG', '.png', '.PNG', '.jpeg', '.JPEG', '.bmp', '.BMP']:
tmp_pl = pa_g.glob('**/*{}'.format(ext))
for t in tmp_pl:
pathlist.append(t)
for path in pathlist:
p_str = str(path)
delim = '/'
if platform == "win32":
delim = '\\'
console.subtask('Loading {0}'.format(p_str.split(delim)[1]))
im = face_recognition.load_image_file(p_str)
encoding = face_recognition.face_encodings(im, num_jitters=self.num_jitters)
for e in encoding:
self.known_face_encodings.append(e)
self.known_face_names.append(label)
示例2: find_and_save_face
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def find_and_save_face(web_file,face_file):
# Load the jpg file into a numpy array
image = face_recognition.load_image_file(web_file)
print(image.dtype)
# Find all the faces in the image
face_locations = face_recognition.face_locations(image)
print("I found {} face(s) in this photograph.".format(len(face_locations)))
for face_location in face_locations:
# Print the location of each face in this image
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# You can access the actual face itself like this:
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.save(face_file)
示例3: encoding_images
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def encoding_images(path):
"""
对path路径下的子文件夹中的图片进行编码,
TODO:
对人脸数据进行历史库中的人脸向量进行欧式距离的比较,当距离小于某个阈值的时候提醒:
如果相似的是本人,则跳过该条记录,并提醒已经存在,否则警告人脸过度相似问题,
:param path:
:return:
"""
with open(name_and_encoding, 'w') as f:
subdirs = [os.path.join(path, x) for x in os.listdir(path) if os.path.isdir(os.path.join(path, x))]
for subdir in subdirs:
print('process image name :', subdir)
person_image_encoding = []
for y in os.listdir(subdir):
print("image name is ", y)
_image = face_recognition.load_image_file(os.path.join(subdir, y))
face_encodings = face_recognition.face_encodings(_image)
name = os.path.split(subdir)[-1]
if face_encodings and len(face_encodings) == 1:
if len(person_image_encoding) == 0:
person_image_encoding.append(face_encodings[0])
known_face_names.append(name)
continue
for i in range(len(person_image_encoding)):
distances = face_recognition.compare_faces(person_image_encoding, face_encodings[0], tolerance=image_thread)
if False in distances:
person_image_encoding.append(face_encodings[0])
known_face_names.append(name)
print(name, " new feature")
f.write(name + ":" + str(face_encodings[0]) + "\n")
break
# face_encoding = face_recognition.face_encodings(_image)[0]
# face_recognition.compare_faces()
known_face_encodings.extend(person_image_encoding)
bb = np.array(known_face_encodings)
print("--------")
np.save(KNOWN_FACE_ENCODINGS, known_face_encodings)
np.save(KNOWN_FACE_NANE, known_face_names)
示例4: get_face_and_save
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def get_face_and_save(path):
image_path = f'{IMAGES_PATH}/{path}'
image = face_recognition.load_image_file(image_path)
locations = face_recognition.face_locations(image)
if len(locations) == 1: # save the face of mm
top, right, bottom, left = locations[0]
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
with open(f'{IMAGES_PATH}/faces/face-{path}', "wb") as f:
pil_image.save(f)
return len(locations)
示例5: get_face_and_save
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def get_face_and_save(filename):
img_path = f"{UPLOAD_DIR}/{filename}"
image = face_recognition.load_image_file(img_path)
locations = face_recognition.face_locations(image)
if len(locations) == 1: # save the face of mm
top, right, bottom, left = locations[0]
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
with open(f"{UPLOAD_DIR}/face-{filename}", "wb") as f:
pil_image.save(f)
return len(locations)
示例6: predict
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def predict(X_img_path, knn_clf=None, model_path=None, distance_threshold=0.6):
"""
Recognizes faces in given image using a trained KNN classifier
:param X_img_path: path to image to be recognized
:param knn_clf: (optional) a knn classifier object. if not specified, model_save_path must be specified.
:param model_path: (optional) path to a pickled knn classifier. if not specified, model_save_path must be knn_clf.
:param distance_threshold: (optional) distance threshold for face classification. the larger it is, the more chance
of mis-classifying an unknown person as a known one.
:return: a list of names and face locations for the recognized faces in the image: [(name, bounding box), ...].
For faces of unrecognized persons, the name 'unknown' will be returned.
"""
if not os.path.isfile(X_img_path) or os.path.splitext(X_img_path)[1][1:] not in ALLOWED_EXTENSIONS:
raise Exception("Invalid image path: {}".format(X_img_path))
if knn_clf is None and model_path is None:
raise Exception("Must supply knn classifier either thourgh knn_clf or model_path")
# Load a trained KNN model (if one was passed in)
if knn_clf is None:
with open(model_path, 'rb') as f:
knn_clf = pickle.load(f)
# Load image file and find face locations
X_img = face_recognition.load_image_file(X_img_path)
X_face_locations = face_recognition.face_locations(X_img)
# If no faces are found in the image, return an empty result.
if len(X_face_locations) == 0:
return []
# Find encodings for faces in the test iamge
faces_encodings = face_recognition.face_encodings(X_img, known_face_locations=X_face_locations)
# Use the KNN model to find the best matches for the test face
closest_distances = knn_clf.kneighbors(faces_encodings, n_neighbors=1)
are_matches = [closest_distances[0][i][0] <= distance_threshold for i in range(len(X_face_locations))]
# Predict classes and remove classifications that aren't within the threshold
return [(pred, loc) if rec else ("unknown", loc) for pred, loc, rec in zip(knn_clf.predict(faces_encodings), X_face_locations, are_matches)]
示例7: recognize_face_from_image_file
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def recognize_face_from_image_file(image_file: str) -> Optional[ndarray]:
if PYROBOY_AVAILABLE:
return FaceRec.get_biggest_face_encoding(image_file)
else:
logger.warning("Falling back to basic Face Recognition functions, since Pyroboy is unavailable!")
image = fr.load_image_file(image_file)
faces = fr.face_encodings(image)
if faces:
return faces[0]
return None
示例8: show_facial_features
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def show_facial_features(image_path):
# Load the jpg file into an array
image = face_recognition.load_image_file(image_path)
# these are the features that will be detected and shown
facial_features = [
'chin',
'left_eyebrow',
'right_eyebrow',
'nose_bridge',
'nose_tip',
'left_eye',
'right_eye',
'top_lip',
'bottom_lip']
blue = ImageColor.getcolor('blue', 'RGB')
# Find all facial landmarks for all the faces in the image
face_landmarks_list = face_recognition.face_landmarks(image)
img_obj = Image.fromarray(image)
# draw lines upon facial features
for face_landmarks in face_landmarks_list:
drawing = ImageDraw.Draw(img_obj)
for facial_feature in facial_features:
drawing.line(face_landmarks[facial_feature], width=2, fill=blue)
# show image
img_obj.show()
示例9: calc_face_encoding
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def calc_face_encoding(image):
# Currently only use first face found on picture
loaded_image = face_recognition.load_image_file(image)
faces = face_recognition.face_encodings(loaded_image)
# If more than one face on the given image was found -> error
if len(faces) > 1:
raise Exception(
"Found more than one face in the given training image.")
# If none face on the given image was found -> error
if not faces:
raise Exception("Could not find any face in the given training image.")
return faces[0]
示例10: detect_faces_in_image
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def detect_faces_in_image(file_stream):
# Load the uploaded image file
img = face_recognition.load_image_file(file_stream)
# Get face encodings for any faces in the uploaded image
uploaded_faces = face_recognition.face_encodings(img)
# Defaults for the result object
faces_found = len(uploaded_faces)
faces = []
if faces_found:
face_encodings = list(faces_dict.values())
for uploaded_face in uploaded_faces:
match_results = face_recognition.compare_faces(
face_encodings, uploaded_face)
for idx, match in enumerate(match_results):
if match:
match = list(faces_dict.keys())[idx]
match_encoding = face_encodings[idx]
dist = face_recognition.face_distance([match_encoding],
uploaded_face)[0]
faces.append({
"id": match,
"dist": dist
})
return {
"count": faces_found,
"faces": faces
}
# <Picture functions> #
# <Controller>
示例11: init_dataset_core
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def init_dataset_core(detection_model, jitters, encoding_models, img_path=None):
"""
Delegated core method for parallelize work
:detection_model
:jitters
:param img_path:
:return:
"""
try:
image = load_image_file(img_path)
except OSError:
log.error(
"init_dataset | === FATAL === | Image {} is corrupted!!".format(img_path))
return None
# log.debug("initDataset | Image loaded! | Searching for face ...")
# Array of w,x,y,z coordinates
# NOTE: Can be used batch_face_locations in order to parallelize the image init, but unfortunately
# it's the only GPU that i have right now. And, of course, i'll try to don't burn it
face_bounding_boxes = face_locations(image, model=detection_model)
face_data = None
if len(face_bounding_boxes) == 1:
log.info(
"initDataset | Image {0} have only 1 face, loading for future training ...".format(img_path))
# Loading the X [data] using 300 different distortion
face_data = face_encodings(image, known_face_locations=face_bounding_boxes, num_jitters=jitters,
model=encoding_models)[0]
else:
log.error(
"initDataset | Image {0} not suitable for training!".format(img_path))
if len(face_bounding_boxes) == 0:
log.error("initDataset | I've not found any face :/ ")
else:
log.error(
"initDataset | Found more than one face, too much for me Sir :&")
return face_data
示例12: get_users
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def get_users():
known_names=[]
known_encods=[]
for i in glob("people/*.jpg"):
img = face_recognition.load_image_file(i)
encoding = face_recognition.face_encodings(img)[0]
known_encods.append(encoding)
known_names.append(i[7:-4])
return known_names, known_encods
示例13: configure
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def configure(self):
import face_recognition
image = face_recognition.load_image_file(self.__file_path)
self.__known_face_encodings = [face_recognition.face_encodings(image)[0]]
示例14: detect
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def detect(args):
arr = face_recognition.load_image_file(args.input)
face_locations = face_recognition.face_locations(arr)
print('found:', len(face_locations))
img = Image.open(args.input)
draw = ImageDraw.Draw(img)
for item in face_locations:
# array uses (row,column) which means (y,x) but I need (x,y)
item = item[1], item[0], item[3], item[2]
draw.rectangle(item, width=3)
img.save(args.output)
示例15: find_same_person
# 需要导入模块: import face_recognition [as 别名]
# 或者: from face_recognition import load_image_file [as 别名]
def find_same_person(person_image_path):
# 获取该人中的所有图片
image_paths = os.listdir(person_image_path)
known_face_encodings = []
for image_path in image_paths:
img_path = os.path.join(person_image_path, image_path)
try:
image = face_recognition.load_image_file(img_path)
encodings = face_recognition.face_encodings(image, num_jitters=10)[0]
known_face_encodings.append(encodings)
except Exception as e:
try:
os.remove(img_path)
except Exception as e:
print(e)
for image_path in image_paths:
try:
print(image_path)
img_path = os.path.join(person_image_path, image_path)
image = face_recognition.load_image_file(img_path)
a_single_unknown_face_encoding = face_recognition.face_encodings(image, num_jitters=10)[0]
results = face_recognition.compare_faces(known_face_encodings, a_single_unknown_face_encoding,
tolerance=0.5)
results = numpy.array(results).astype(numpy.int64)
if numpy.sum(results) > 5:
main_path = os.path.join(person_image_path, '0.jpg')
if os.path.exists(main_path):
os.remove(main_path)
shutil.copyfile(img_path, main_path)
break
except:
pass