import cv2
from yangke.common.config import logger
from yangke.base import show_pic


def init_capture(width=1280, height=720):
    """
    初始化视频流，分辨率可选1920*1080， 1280*720等

    :param width: 视频分辨率的宽
    :param height: 视频分辨率的高
    """
    logger.debug(f"尝试打开视频流")
    # cap = cv2.VideoCapture(0, cv2.CAP_MSMF)  # 特别慢
    cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
    if cap.isOpened():
        logger.debug("视频流打开成功")
    else:
        logger.debug(f"视频流打开失败，请检查hdmi视频流信号是否已经被OBS等软件采集")
    # 设置分辨率
    cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)  # 1280, 720
    cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
    # logger.debug(f"设置分辨率为：{w}x{h}")
    return cap


def capture_window(cap):
    """
    获取视频流的一帧

    :param cap: 视频流
    """
    ret, frame = cap.read()
    img = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
    return img


def release_capture(cap):
    cap.release()


def test():
    cap0 = cv2.VideoCapture(0, cv2.CAP_DSHOW)  # 视频流
    # cap0.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc('M', 'J', 'P', 'G'))  #读取视频格式
    # 设置分辨率
    cap0.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    cap0.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)
    while cap0.isOpened():
        ret, frame = cap0.read()
        if ret:
            cv2.imshow("frame", frame)
        pass
        if cv2.waitKey(1000) & 0xFF == ord("q"):
            break
        pass
    pass
    cap0.release()
    cv2.destroyAllWindows()


if __name__ == "__main__":
    cap0 = init_capture()
    while cap0.isOpened():
        snapshot = capture_window(cap0)
