已安装CUDA/CuDNN,如何让人脸表情识别Python脚本启用GPU?
问题:人脸表情识别脚本无法利用GPU加速,仅用CPU运行导致速度缓慢
已安装CUDA和CuDNN,命令行执行tf.test.is_gpu_available()返回True,但运行以下人脸表情识别脚本时始终仅使用CPU,速度极慢。
import tkinter as tk from tkinter import messagebox from PIL import Image, ImageTk import cv2 import numpy as np import face_recognition import os import imutils import time from imutils.video import VideoStream from keras.models import load_model from keras.preprocessing import image import tensorflow as tf # Tkinter penceresini oluştur root = tk.Tk() root.title("Yüz Tanıma ve Duygu Analizi") # Frame'leri oluştur main_frame = tk.Frame(root) main_frame.pack() left_frame = tk.Frame(main_frame) left_frame.pack(side=tk.LEFT) right_frame = tk.Frame(main_frame) right_frame.pack(side=tk.RIGHT) # Kamera görüntüsü için etiket video_label = tk.Label(left_frame) video_label.pack() # Yüz Tanıma ve Duygu Analizi etiketi label = tk.Label(right_frame, text="Yüz Tanıma ve Duygu Analizi", font=("Helvetica", 16)) label.pack() # Uygulamayı kapatacak buton close_button = tk.Button(right_frame, text="Uygulamayı Kapat", command=root.quit) close_button.pack() # Eğitilmiş duygu analizi modelini yükle model = load_model('model_1.h5') label_dict = {0: 'Kizgin', 1: 'İgrenme', 2: 'Korku', 3: 'Mutlu', 4: 'Notr', 5: 'Uzgun', 6: 'Saskin'} # Yüz tanıma için kullanılacak parametreler DEFAULT_PROTOTXT = "deploy.prototxt.txt" DEFAULT_MODEL = "res10_300x300_ssd_iter_140000.caffemodel" DEFAULT_CONFIDENCE = 0.5 # Caffe modelini diskten yükle net = cv2.dnn.readNetFromCaffe(DEFAULT_PROTOTXT, DEFAULT_MODEL) # Video akışını başlat vs = VideoStream(src=0).start() time.sleep(2.0) # Kamera görüntüsünü güncelle def update_video(): frame = vs.read() frame = imutils.resize(frame, width=900) (h, w) = frame.shape[:2] blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0, (300, 300), (104.0, 177.0, 123.0)) net.setInput(blob) detections = net.forward() for i in range(0, detections.shape[2]): confidence = detections[0, 0, i, 2] if confidence < DEFAULT_CONFIDENCE: continue box = detections[0, 0, i, 3:7] * np.array([w, h, w, h]) (startX, startY, endX, endY) = box.astype("int") face_roi = frame[startY:endY, startX:endX] face_gray = cv2.cvtColor(face_roi, cv2.COLOR_BGR2GRAY) face_img = cv2.resize(face_gray, (48, 48)) face_img_array = image.img_to_array(face_img) face_img_array = np.expand_dims(face_img_array, axis=0) face_img_array = np.expand_dims(face_img_array, axis=-1) predictions = model.predict(face_img_array) emotion_label_index = np.argmax(predictions) predicted_emotion = label_dict[emotion_label_index] cv2.rectangle(frame, (startX, startY), (endX, endY), (0, 0, 255), 2) cv2.putText(frame, f'Duygu: {predicted_emotion}', (startX, startY - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA) # Yüz eşleştirme için resimleri yükle image_folder = "image" # Resimlerin bulunduğu klasör known_faces = [] known_face_names = [] for file in os.listdir(image_folder): if file.endswith(".jpg"): file_path = os.path.join(image_folder, file) img = face_recognition.load_image_file(file_path) encoding = face_recognition.face_encodings(img)[0] # Her bir resmin yüz kodlamasını al known_faces.append(encoding) known_face_names.append(os.path.splitext(file)[0]) # Dosya adını yüz ismi olarak ekle # Yüz eşleştirme face_locations = face_recognition.face_locations(frame) unknown_face_encodings = face_recognition.face_encodings(frame, face_locations) for face_encoding in unknown_face_encodings: matches = face_recognition.compare_faces(known_faces, face_encoding) name = "Bilinmiyor" # Eğer eşleşme yoksa if True in matches: first_match_index = matches.index(True) name = known_face_names[first_match_index] # Yüzün etrafına isim yazdır cv2.putText(frame, name, (startX, startY - 30), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (255, 255, 255), 2, cv2.LINE_AA) frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) photo = ImageTk.PhotoImage(image=Image.fromarray(frame)) video_label.config(image=photo) video_label.image = photo video_label.after(10, update_video) # Kamera görüntüsünü göster update_video() # Yeni label oluştur ve konumlandır label_text = tk.Label(right_frame, text="İsim Giriniz") label_text.pack() # Yeni metin kutusu oluştur ve konumlandır textbox = tk.Entry(right_frame) textbox.pack() def save_photo(): # Metin kutusundaki değeri al photo_name = textbox.get() # Eğer metin kutusu boşsa rastgele bir isimle kaydet if not photo_name.strip(): # Uyarı mesajı messagebox.showwarning("Uyarı", "Fotoğraf adı boş olamaz. Lütfen bir ad girin.") return # Kamera görüntüsünü al frame = vs.read() # Fotoğrafı kaydet image_folder = "C:/Users/Paban/Desktop/FaceDetection_Realtime/image" file_path = os.path.join(image_folder, f"{photo_name}.jpg") cv2.imwrite(file_path, frame) def show_photo(): # Metin kutusundaki değeri al photo_name = textbox.get() # Eğer metin kutusu boşsa uyarı mesajı göster if not photo_name.strip(): messagebox.showwarning("Uyarı", "Fotoğraf adı boş olamaz. Lütfen bir ad girin.") return # Dosya yolu oluştur image_folder = "C:/Users/Paban/Desktop/FaceDetection_Realtime/image" file_path = os.path.join(image_folder, f"{photo_name}.jpg") # Fotoğrafın varlığını kontrol et if not os.path.isfile(file_path): messagebox.showwarning("Uyarı", "Belirtilen isimde bir fotoğraf bulunamadı.") return # Fotoğrafı göster img = Image.open(file_path) img.show() # Yeni butonu oluştur ve fonksiyonu bağla save_button = tk.Button(right_frame, text="Fotoğrafı Kaydet", command=save_photo) save_button.pack() # Yeni butonu oluştur ve fonksiyonu bağla show_button = tk.Button(right_frame, text="Fotoğrafı Göster", command=show_photo) show_button.pack() # Tkinter penceresini çalıştır root.mainloop() # Temizlik işlemleri cv2.destroyAllWindows() vs.stop()
解决方案
1. 强制TensorFlow/Keras使用GPU
在脚本开头添加GPU配置代码,确保TensorFlow优先分配GPU资源并启用内存增长(避免显存被占满):
import tensorflow as tf # 配置GPU内存动态增长 gpus = tf.config.list_physical_devices('GPU') if gpus: try: for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) print(f"检测到 {len(gpus)} 个物理GPU,已启用动态内存增长") except RuntimeError as e: print(e)
2. 让OpenCV的DNN模型使用GPU
你代码中用于人脸检测的Caffe模型默认用CPU运行,添加以下代码强制其使用GPU:
# 加载Caffe模型后添加 net.setPreferableBackend(cv2.dnn.DNN_BACKEND_CUDA) net.setPreferableTarget(cv2.dnn.DNN_TARGET_CUDA)
3. 优化face_recognition库的GPU支持
face_recognition依赖的dlib默认是CPU版本,需重新安装带CUDA支持的dlib:
- 卸载现有dlib:
pip uninstall dlib - 安装CUDA版本:
pip install dlib --install-option="--use-cuda"
4. 避免循环内重复加载数据
你的update_video()函数每次循环都会重新加载人脸编码数据,这会极大消耗CPU。把这部分代码移到函数外部,仅执行一次:
# 移到update_video函数外,只加载一次 known_faces = [] known_face_names = [] image_folder = "image" for file in os.listdir(image_folder): if file.endswith(".jpg"): file_path = os.path.join(image_folder, file) img = face_recognition.load_image_file(file_path) encoding = face_recognition.face_encodings(img)[0] known_faces.append(encoding) known_face_names.append(os.path.splitext(file)[0]) def update_video(): # 原函数内容,移除重复加载known_faces的代码 ...
5. 验证GPU使用状态
在脚本开头添加验证代码,确认各模块是否正确识别GPU:
# 验证TensorFlow GPU print("TensorFlow GPU可用:", tf.test.is_gpu_available()) print("可用GPU设备:", tf.config.list_physical_devices('GPU')) # 验证OpenCV CUDA支持 print("OpenCV CUDA设备数量:", cv2.cuda.getCudaEnabledDeviceCount())
内容的提问来源于stack exchange,提问作者paban
相关产品推荐
相关产品推荐

