You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

M1 MacBook Pro上Keras安装使用与代码问题排查(PyCharm适配)

M1 MacBook Pro上Keras预训练模型部署与PyCharm适配指南

一、M1专属环境搭建(Miniconda)

M1为苹果硅架构,需使用arm64版本依赖包,步骤如下:

  1. 安装苹果硅版本Miniconda,创建并激活专属环境:
conda create -n keras_env python=3.9
conda activate keras_env
  1. 安装适配M1的TensorFlow/Keras(Keras已整合进TensorFlow,无需单独安装):
conda install -c apple tensorflow-deps
pip install tensorflow-macos tensorflow-metal
  1. 安装OpenCV:
pip install opencv-python

二、代码错误排查与修正

原代码存在3个核心问题,修正后即可正常运行:

1. Keras导入路径错误

当前官方Keras已作为TensorFlow的子模块维护,原代码的from keras...导入会导致兼容问题,替换为:

from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import model_from_json

2. Haar分类器文件路径问题

直接写文件名可能找不到文件,改用OpenCV自带的分类器路径:

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

3. 模型文件路径验证

确保facial_expression_model_structure.json和facial_expression_model_weights.h5放在代码的同一目录下,若不在,需填写绝对路径(如/Users/xxx/Documents/model.json)。

三、PyCharm环境适配

  1. 配置项目解释器:打开PyCharm → File → Settings → Project: xxx → Python Interpreter → 选择刚才创建的conda env: keras_env。
  2. 授予摄像头权限:打开系统设置 → 隐私与安全性 → 摄像头 → 勾选PyCharm。
  3. 设置工作目录:运行代码前,右键代码文件 → Run 'xxx' → 点击编辑配置 → 将Working directory设置为代码和模型文件所在的文件夹。

四、修正后的完整代码

import cv2
import numpy as np
from tensorflow.keras.preprocessing import image
from tensorflow.keras.models import model_from_json


# Load the pre-trained model
model = model_from_json(open("facial_expression_model_structure.json", "r").read())
model.load_weights('facial_expression_model_weights.h5')

# Define the emotions
emotions = ('angry', 'disgust', 'fear', 'happy', 'sad', 'surprise', 'neutral')

# Open a connection to the webcam
cap = cv2.VideoCapture(0)

while True:
    # Capture a frame from the webcam
    ret, frame = cap.read()
    if not ret:
        break  # 防止摄像头读取失败导致崩溃

    # Convert the frame to grayscale
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # Detect faces in the frame using a Haar Cascade classifier
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # For each detected face
    for (x, y, w, h) in faces:
        # Draw a rectangle around the face
        cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # Extract the region of interest (ROI) from the grayscale image
        roi_gray = gray[y:y + h, x:x + w]

        # Resize the ROI to match the input size of the model
        roi = cv2.resize(roi_gray, (48, 48))
        roi = roi.astype('float32')
        roi /= 255
        roi = np.expand_dims(roi, axis=0)
        roi = np.expand_dims(roi, axis=-1)

        # Make a prediction using the pre-trained model
        prediction = model.predict(roi, verbose=0)[0]  # verbose=0关闭预测日志

        # Find the emotion with the highest probability
        max_index = np.argmax(prediction)
        emotion = emotions[max_index]

        # Display the emotion on the image
        cv2.putText(frame, emotion, (x + 20, y - 60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)

    # Display the resulting frame with detected faces and emotions
    cv2.imshow('Emotion Detection', frame)

    # Exit the loop when 'q' key is pressed
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release the webcam and close all OpenCV windows
cap.release()
cv2.destroyAllWindows()

内容的提问来源于stack exchange,提问作者suiiisukeee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 20:27:47