从保存的图像中预测情绪(OpenCV 网络摄像头)

Posted

技术标签:

【中文标题】从保存的图像中预测情绪(OpenCV 网络摄像头)【英文标题】:Predicting emotions from saved image (OpenCV web cam) 【发布时间】:2021-05-04 01:57:46 【问题描述】:

我有一个 OpenCV 代码,它输入来自网络摄像头的每一帧并输出预测的面部表情。 如何改为预测保存的图像? (我不想要网络摄像头结果,我希望我的情绪预测能够预测我文件夹中保存的图像)

# emotions will be displayed on your face from the webcam feed
elif mode == "display":
    model.load_weights('model.h5')

    # prevents openCL usage and unnecessary logging messages
    cv2.ocl.setUseOpenCL(False)

    # dictionary which assigns each label an emotion (alphabetical order)
    emotion_dict = 0: "Angry", 1: "Disgusted", 2: "Fearful", 3: "Happy", 4: "Neutral", 5: "Sad", 6: "Surprised"

    # start the webcam feed
    cap = cv2.VideoCapture(0)
    while True:
        # Find haar cascade to draw bounding box around face
        ret, frame = cap.read()
        if not ret:
            break
        facecasc = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = facecasc.detectMultiScale(gray,scaleFactor=1.3, minNeighbors=5)

        for (x, y, w, h) in faces:
            cv2.rectangle(frame, (x, y-50), (x+w, y+h+10), (255, 0, 0), 2)
            roi_gray = gray[y:y + h, x:x + w]
            cropped_img = np.expand_dims(np.expand_dims(cv2.resize(roi_gray, (48, 48)), -1), 0)
            prediction = model.predict(cropped_img)
            maxindex = int(np.argmax(prediction))
            cv2.putText(frame, emotion_dict[maxindex], (x+20, y-60), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)

        cv2.imshow('Video', cv2.resize(
            frame, (1600, 960), interpolation=cv2.INTER_CUBIC))
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

【问题讨论】:

如果您知道如何捕获图像,则必须知道如何从文件中读取。 【参考方案1】:

只需删除这些行:

cap = cv2.VideoCapture(0)
while True:
    # Find haar cascade to draw bounding box around face
    ret, frame = cap.read()
    if not ret:
        break

改为放置:

frame = cv2.imread('your_path.jpg',0)

【讨论】:

以上是关于从保存的图像中预测情绪(OpenCV 网络摄像头)的主要内容,如果未能解决你的问题,请参考以下文章

如何opencv读取摄像头并保存每一帧图像

如何从网络摄像头 OpenCV 裁剪圆形图像并删除背景

OpenCv - 从网络摄像头捕获帧时发生内存泄漏

我的 OpenCV 实时网络摄像头演示没有显示准​​确的情绪

opencv调用摄像头函数

OpenCV4Android SVM 没有给出正确的预测