I am trying to switch between OBS scenes automatically based on whether a face is detected in a webcam feed. I am using the OBS WebSocket API to connect to OBS and switch between scenes. However, I am encountering an issue where the scene does not switch even though a face is detected. The program runs without any errors, but the debug output shows that the current scene is always an empty dictionary {}. Here is a sample of my code:
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()
I am getting this reply from the OBS WebSocket:
Connected to OBS WebSocket version: Unknown.Unknown.Unknown Current scene: {} Switching to scene: LIVE
It seems that the GetCurrentScene() function is not returning the correct scene. Can someone please help me understand what is causing this issue and how I can fix it?
Here's something I found that might help: