Skip to content

I can't get a screenshot of the area with this code #99

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wangbaoyi opened this issue Nov 14, 2024 · 0 comments
Open

I can't get a screenshot of the area with this code #99

wangbaoyi opened this issue Nov 14, 2024 · 0 comments

Comments

@wangbaoyi
Copy link

import obsws_python as obs
import numpy as np
import base64
import cv2
import sys
import time # 导入 time 模块

连接到 OBS WebSocket

cl = obs.ReqClient(host='192.168.31.38', port=9988, password="123456")

获取当前活动场景名称

current_scene = cl.get_current_program_scene().scene_name
print(f"当前活动场景名称: {current_scene}")

获取当前场景中的所有源名称

scene_items = cl.get_scene_item_list(current_scene).scene_items
print("当前场景中的源名称:", [item['sourceName'] for item in scene_items])

确保源名称正确

source = "aaa" # 更新为实际存在的源名称

while True:
try:
start_time = time.time() # 记录开始时间

    # 获取源截图
    Screenshot = cl.get_source_screenshot(source, "jpg", 416, 416, 30)
    Screenshot = Screenshot.image_data

    # 检查截图数据是否为空
    if not Screenshot:
        print("截图数据为空,可能源名称不正确或未能成功获取截图。")
        break

    # 去掉 base64 前缀
    if Screenshot.startswith("data:image/jpg;base64,"):
        Screenshot = Screenshot.replace("data:image/jpg;base64,", "")

    # 长度不为4整数倍的base64串需要用"='补全
    num = len(Screenshot) % 4
    if num != 0:
        Screenshot = Screenshot + '=' * (4 - num)
    
    # 解码图像数据
    img = base64.b64decode(Screenshot)
    img_array = np.frombuffer(img, np.uint8)
    img = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
    #改变图片大小
    # img = cv2.resize(img, (640, 640))
    # 检查解码后的图像是否有效
    if img is None or img.size == 0:
        print("解码后的图像无效。")
        break
    
    # 实时显示图像
    cv2.imshow("img", img)
    # 将窗口移动到左上角
    cv2.moveWindow("img", 800, 0)
    
    # 记录结束时间并计算耗时
    end_time = time.time()
    elapsed_time_ms = (end_time - start_time) * 1000
    print(f"处理耗时: {elapsed_time_ms:.2f} ms")

    # 检查是否按下 'q' 键以退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
except Exception as e:
    print(f"获取源截图失败: {e}")
    break

cv2.destroyAllWindows() # 关闭所有 OpenCV 窗口

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant