Python 无法使用load_model()加载模型
执行以下所有导入时没有任何错误Python 无法使用load_model()加载模型,python,opencv,keras,face-recognition,dlib,Python,Opencv,Keras,Face Recognition,Dlib,执行以下所有导入时没有任何错误 import cv2 import numpy as np import dlib import glob from scipy.spatial import distance from imutils import face_utils from keras.models import load_model from fr_utils import * from inception_blocks_v2 import * 当我尝试导入一个预先训练过的模型“fac
import cv2
import numpy as np
import dlib
import glob
from scipy.spatial import distance
from imutils import face_utils
from keras.models import load_model
from fr_utils import *
from inception_blocks_v2 import *
当我尝试导入一个预先训练过的模型“face-rec_Google.h5”时,它已经使用facenet进行了训练。文件('face-rec_Google.h5')位于我的项目文件夹中
x = load_model('face-rec_Google.h5')
我得到以下错误
ValueError: Initializer for variable conv1_4/kernel/ is from inside a
control-flow construct, such as a loop or conditional. When creating a
variable inside a loop or conditional,
use a lambda as the initializer.
下面是整个人脸识别代码:
import cv2
import numpy as np
import dlib
import glob
from scipy.spatial import distance
from imutils import face_utils
from keras.models import load_model
from fr_utils import *
from inception_blocks_v2 import *
detector = dlib.get_frontal_face_detector()
x = load_model('face-rec_Google.h5')
print("Total Params:", x.count_params())
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")
thresh = 0.25
def eye_aspect_ratio(eye):
A = distance.euclidean(eye[1], eye[5])
B = distance.euclidean(eye[2], eye[4])
C = distance.euclidean(eye[0], eye[3])
ear = (A + B) / (2.0 * C)
return ear
def recognize_face(face_descriptor, database):
encoding = img_to_encoding(face_descriptor, FRmodel)
min_dist = 100
identity = None
# Loop over the database dictionary's names and encodings.
for (name, db_enc) in database.items():
# Compute L2 distance between the target "encoding" and the current "emb" from the database.
dist = np.linalg.norm(db_enc - encoding)
print('distance for %s is %s' % (name, dist))
# If this distance is less than the min_dist, then set min_dist to dist, and identity to name
if dist < min_dist:
min_dist = dist
identity = name
if int(identity) <=4:
return str('Akshay'), min_dist
if int(identity) <=8:
return str('Apoorva'), min_dist
def extract_face_info(img, img_rgb, database,ear):
faces = detector(img_rgb)
x, y, w, h = 0, 0, 0, 0
if len(faces) > 0:
for face in faces:
(x, y, w, h) = face_utils.rect_to_bb(face)
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 255, 0), 2)
image = img[y:y + h, x:x + w]
name, min_dist = recognize_face(image, database)
if ear > thresh:
if min_dist < 0.1:
cv2.putText(img, "Face : " + name, (x, y - 50), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
cv2.putText(img, "Dist : " + str(min_dist), (x, y - 20), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 255, 0), 2)
else:
cv2.putText(img, 'No matching faces', (x, y - 20), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 255), 2)
else:
cv2.putText(img, 'Eyes Closed', (x, y - 20), cv2.FONT_HERSHEY_PLAIN, 1.5, (0, 0, 255), 2)
def initialize():
#load_weights_from_FaceNet(FRmodel)
#we are loading model from keras hence we won't use the above method
database = {}
# load all the images of individuals to recognize into the database
for file in glob.glob("images//"):
identity = os.path.splitext(os.path.basename(file))[0]
database[identity] = fr_utils.img_path_to_encoding(file, FRmodel)
return database
def recognize():
database = initialize()
cap = cv2.VideoCapture(0)
(lStart, lEnd) = face_utils.FACIAL_LANDMARKS_IDXS["left_eye"]
(rStart, rEnd) = face_utils.FACIAL_LANDMARKS_IDXS["right_eye"]
while True:
ret, img = cap.read()
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
subjects = detector(gray, 0)
for subject in subjects:
shape = predictor(gray, subject)
shape = face_utils.shape_to_np(shape) # converting to NumPy Array
leftEye = shape[lStart:lEnd]
rightEye = shape[rStart:rEnd]
leftEAR = eye_aspect_ratio(leftEye)
rightEAR = eye_aspect_ratio(rightEye)
ear = (leftEAR + rightEAR) / 2.0
leftEyeHull = cv2.convexHull(leftEye)
rightEyeHull = cv2.convexHull(rightEye)
cv2.drawContours(img, [leftEyeHull], -1, (0, 255, 0), 1)
cv2.drawContours(img, [rightEyeHull], -1, (0, 255, 0), 1)
extract_face_info(img, img_rgb, database,ear)
cv2.imshow('Recognizing faces', img)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
recognize()
导入cv2
将numpy作为np导入
导入dlib
导入glob
从scipy.spatial导入距离
从imutils导入面\u utils
从keras.models导入负载_模型
从fr_utils导入*
从开始\u块\u v2导入*
探测器=dlib.获取正面探测器()
x=加载模型('face-rec_Google.h5'))
打印(“总参数:,x.计数参数())
predictor=dlib.shape\u predictor(“shape\u predictor\u 68\u face\u landmarks.dat”)
thresh=0.25
def眼宽比(眼):
A=距离。欧几里德(眼睛[1],眼睛[5])
B=距离。欧几里德(眼睛[2],眼睛[4])
C=距离。欧几里德(眼睛[0],眼睛[3])
ear=(A+B)/(2.0*C)
回音耳
def识别面(面描述符,数据库):
编码=img_到_编码(面描述符,FRmodel)
最小距离=100
标识=无
#循环数据库字典的名称和编码。
对于数据库中的(名称,db_enc)。项()
#计算目标“编码”和数据库中当前“emb”之间的L2距离。
dist=np.linalg.norm(db_enc-编码)
打印(“%s”的距离为“%s%”(名称,距离))
#如果此距离小于“最小距离”,则将“最小距离”设置为“距离”,将“标识”设置为“名称”
如果距离小于最小距离:
最小距离=距离
标识=名称
如果int(标识)阈值:
如果最小距离<0.1:
cv2.putText(img,“Face:+name,(x,y-50),cv2.FONT\u HERSHEY\u PLAIN,1.5,(0,255,0),2)
cv2.putText(img,“Dist:+str(min_Dist),(x,y-20),cv2.FONT_HERSHEY_PLAIN,1.5,(0,255,0),2)
其他:
cv2.putText(img,'无匹配面',(x,y-20),cv2.FONT\u HERSHEY\u PLAIN,1.5,(0,0,255),2)
其他:
cv2.putText(img,“闭眼”(x,y-20),cv2.FONT\u HERSHEY\u PLAIN,1.5,(0,0,255),2)
def初始化():
#从面网(FRmodel)加载重量
#我们正在从keras加载模型,因此我们不会使用上述方法
数据库={}
#将要识别的个人的所有图像加载到数据库中
对于glob.glob(“images/”)中的文件:
identity=os.path.splitext(os.path.basename(文件))[0]
数据库[identity]=fr_utils.img_path_to_编码(文件,FRmodel)
返回数据库
def recognize():
数据库=初始化()
cap=cv2.视频捕获(0)
(lStart,lEnd)=面部特征。面部标志物[“左眼”]
(rStart,rEnd)=面部特征。面部标志物[“右眼”]
尽管如此:
ret,img=cap.read()
img_rgb=cv2.cvt颜色(img,cv2.COLOR_BGR2RGB)
灰色=cv2.CVT颜色(img,cv2.COLOR\U BGR2GRAY)
受试者=检测器(灰色,0)
关于主题中的主题:
形状=预测值(灰色,主体)
shape=face_utils.shape_to_np(shape)#转换为NumPy数组
leftEye=形状[lStart:lEnd]
右眼=形状[rStart:rEnd]
左眼=眼睛与纵横比(左眼)
右眼=眼睛与纵横比(右眼)
ear=(左耳+右耳)/2.0
leftEyeHull=cv2.convexHull(左眼)
右眼外壳=cv2.凸面外壳(右眼)
cv2.等高线图(img,[leftEyeHull],-1,(0,255,0),1)
cv2.等高线图(img,[rightEyeHull],-1,(0,255,0,1)
提取面部信息(img、img、rgb、数据库、ear)
cv2.imshow(“识别人脸”,img)
如果cv2.waitKey(1)=ord('q'):
打破
第1章释放()
cv2.destroyAllWindows()
承认
您使用的Keras版本是什么
我的一个建议是尝试将Keras更新到其最新版本(撰写此评论时为2.2.4)
确保您还将keras.applications和keras.preprocessing更新为其最新版本
如果这不起作用,您可以尝试以下选项:
首先卸载Keras及其应用程序+预处理(对不起,我忘了添加这个)
然后,更新TensorFlow的版本。完成此步骤后,请遵循以下建议
通过tensorflow
尝试使用load\u model
方法。
例如:从
tensorflow.keras.models导入load\u model
这里是我的依赖项keras-2.2.4,keras应用程序-1.0.6 keras预处理-1.0.5 tensorflow-1.8从tensorflow.keras.models导入load\u model导致modulenofounderror卸载keras。因为Keras现在是tensorflow后端的一部分,所以不需要单独安装Keras。升级TensorFlow并卸载Keras。另外,确保以相同的方式导入所有内容;示例:使用tensorflow.keras.xThanks代替keras.x它工作的人忘记重命名tensorflow.keras我的其他文件,因此错误持续了一段时间。没有问题,我很高兴它解决了您的问题!:你能包括错误的完整回溯吗?