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

Python结合OBS WebSocket人脸检测场景切换异常排查求助

问题描述

我正在尝试基于摄像头画面的人脸检测结果,通过Python调用OBS WebSocket API自动切换OBS场景。目前遇到的问题是:即使检测到人脸,场景也无法切换;程序无报错,但调试输出显示GetCurrentScene()始终返回空字典{},且无法正常获取OBS WebSocket版本信息。

代码实现
import cv2
import time
import numpy as np
from obswebsocket import obsws, requests, events

# OBS WebSocket connection settings
host = "localhost"
port = 4455
password = "PLACEHOLDER"

# Scene names
live_scene = "LIVE"
afk_scene = "AFK"

# Global variable to store the current scene name
current_scene_name = ""

# Connect to OBS
ws = obsws(host, port, password)
print("Connecting to OBS WebSocket at {}:{}".format(host, port))
ws.connect()

try:
    version_info = ws.call(requests.GetVersion())
    print("Connected to OBS WebSocket version: {}.{}.{}".format(
        version_info.data().get("majorVersion", "Unknown"),
        version_info.data().get("minorVersion", "Unknown"),
        version_info.data().get("patchVersion", "Unknown")
    ))
    scenes = ws.call(requests.GetSceneList())
    print("Available scenes:", [scene["name"] for scene in scenes.data()["scenes"]])  # Added debug output
except Exception as e:
    print("Error connecting to OBS WebSocket:")
    print(type(e))
    print(e.args)
    print(e)

# Initialize webcam
cap = cv2.VideoCapture(0)

# Initialize face detection
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

while True:
    ret, frame = cap.read()

    if ret:
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.1, 4)

        if len(faces) > 0:
            print("Face detected")
            current_scene = ws.call(requests.GetCurrentScene())
            print("Current scene:", current_scene.data())  # Added debug output
            current_scene_name = current_scene.data().get("name", "Unknown")
            ws.call(requests.SetCurrentScene(scene_name=live_scene))
            print("Switching to scene:", live_scene)
        else:
            print("No face detected")
            current_scene = ws.call(requests.GetCurrentScene())
            print("Current scene:", current_scene.data())  # Added debug output
            current_scene_name = current_scene.data().get("name", "Unknown")
            ws.call(requests.SetCurrentScene(scene_name=afk_scene))
            print("Switching to scene:", afk_scene)

        time.sleep(1)

    else:
        print("Error reading frame from webcam")
        break

cap.release()
cv2.destroyAllWindows()
程序输出
Connected to OBS WebSocket version: Unknown.Unknown.Unknown
Current scene: {}
Switching to scene: LIVE
问题分析与解决方法

核心原因

你使用的obswebsocket库仅兼容OBS WebSocket 4.x版本,但当前OBS默认安装的是5.x版本,两者API协议完全不兼容。旧库无法解析新版本的响应格式,因此出现返回空字典、无法获取版本信息的情况。

具体解决步骤

  1. 替换兼容5.x版本的库
    卸载旧库,安装官方推荐的适配5.x版本的obs-websocket-py:

    pip uninstall obswebsocket
    pip install obs-websocket-py
    
  2. 修改代码适配新API
    新库的请求方法、数据结构均有变化,以下是调整后的完整代码:

    import cv2
    import time
    from obswebsocket import obsws, requests
    
    # OBS WebSocket 5.x连接配置
    host = "localhost"
    port = 4455
    password = "PLACEHOLDER"
    
    live_scene = "LIVE"
    afk_scene = "AFK"
    
    # 建立连接
    ws = obsws(host, port, password)
    ws.connect()
    
    try:
        # 获取版本信息(新API方法)
        version_resp = ws.call(requests.GetVersion())
        version_data = version_resp.get_data()
        print(f"Connected to OBS WebSocket version: {version_data['obsWebSocketVersion']}")
        
        # 获取场景列表(新API方法)
        scenes_resp = ws.call(requests.GetSceneList())
        scenes = scenes_resp.get_data()["scenes"]
        print("Available scenes:", [scene["sceneName"] for scene in scenes])
    except Exception as e:
        print(f"Error connecting to OBS WebSocket: {e}")
    
    # 初始化摄像头与人脸检测
    cap = cv2.VideoCapture(0)
    face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
    
    while True:
        ret, frame = cap.read()
        if not ret:
            print("Error reading frame from webcam")
            break
    
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.1, 4)
    
        target_scene = live_scene if len(faces) > 0 else afk_scene
        
        # 获取当前程序场景(新API方法)
        current_scene_resp = ws.call(requests.GetCurrentProgramScene())
        current_scene = current_scene_resp.get_data()["currentProgramSceneName"]
        
        # 仅当场景不一致时切换,减少无效请求
        if current_scene != target_scene:
            ws.call(requests.SetCurrentProgramScene(sceneName=target_scene))
            print(f"Switched to scene: {target_scene}")
        else:
            print(f"Already in scene: {target_scene}")
    
        time.sleep(1)
    
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()
    ws.disconnect()
    
  3. 检查OBS WebSocket设置

    • 打开OBS,进入工具 > obs-websocket设置
    • 确认端口为4455,密码与代码中PLACEHOLDER一致
    • 勾选启用Web服务器
  4. 额外优化建议

    • 增加连续帧人脸检测判断(比如连续2帧检测到人脸再切换),避免误触发
    • 程序结束时调用ws.disconnect()关闭连接,避免资源泄漏

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 01:52:35