import time

from PIL import Image
import cv2
# class GetImage:
#     def __init__(self, cam_index=0, width=1920, height=1080):
#         self.cap = cv2.VideoCapture(cam_index,cv2.CAP_DSHOW)
#
#         if not self.cap.isOpened():
#             raise RuntimeError(f"无法打开摄像头 {cam_index}")
#         self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
#         self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
#         print(f"✅ 摄像头 {cam_index} 打开成功，分辨率 {width}x{height}")
#     def get_frame(self):
#         ret, im_opencv = self.cap.read()
#         im_opencv = cv2.cvtColor(im_opencv, cv2.COLOR_BGR2RGB)  # rgb 修改通道数并转换图像
#         im_opencv = im_opencv[30:30+720, 0:1280]#裁剪尺寸
#         im_PIL = Image.fromarray(im_opencv)  # 图像改成对象类型
#
#         return [im_opencv, im_PIL]
#     def release(self):
#         self.cap.release()
#         cv2.destroyAllWindows()
#         print("🔚 摄像头已释放")
#     def __del__(self):
#         # 以防忘记手动释放
#         if hasattr(self, "cap") and self.cap.isOpened():
#             self.release()
#
# get_image = GetImage()
#
# if __name__ == '__main__':
#     while True:
#         if cv2.waitKey(1) & 0xFF == ord('q'):
#             break
#         a=get_image.get_frame()
#         cv2.imshow('image',a[0])
#         print(a[0].shape)
#
#
#     cv2.destroyAllWindows()

import threading

class GetImage:
    def __init__(self, cam_index=0, width=1920, height=1080):
        self.cap = cv2.VideoCapture(cam_index, cv2.CAP_DSHOW)
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        self.frame = None
        self.running = True
        threading.Thread(target=self.update, daemon=True).start()

    def update(self):
        while self.running:
            ret, frame = self.cap.read()
            if ret:
                self.frame = frame

    def get_frame(self):
        if self.frame is None:
            return None
        im_opencv = cv2.cvtColor(self.frame, cv2.COLOR_BGR2RGB)
        im_opencv = im_opencv[30:30+720, 0:1280]
        im_PIL = Image.fromarray(im_opencv)
        return [im_opencv, im_PIL]

    def release(self):
        self.running = False
        time.sleep(0.2)
        self.cap.release()
        cv2.destroyAllWindows()
get_image = GetImage()