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):
        print(f"🔧 正在初始化采集卡 {cam_index}...")
        self.cap = cv2.VideoCapture(cam_index, cv2.CAP_DSHOW)
        if not self.cap.isOpened():
            print(f"⚠️ DSHOW模式失败，尝试默认模式...")
            self.cap = cv2.VideoCapture(cam_index)
        
        if not self.cap.isOpened():
            print(f"❌ 无法打开采集卡 {cam_index}")
            self.cap = None
            return
            
        self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        self.frame = None
        self.running = True
        self.cam_index = cam_index
        
        # 启动更新线程
        threading.Thread(target=self.update, daemon=True).start()
        
        # 等待几帧确保采集卡正常工作
        import time
        time.sleep(1.0)
        print(f"✅ 采集卡 {cam_index} 初始化完成")

    def update(self):
        while self.running and self.cap is not None:
            ret, frame = self.cap.read()
            if ret:
                self.frame = frame
            else:
                print(f"⚠️ 采集卡 {self.cam_index} 读取失败")

    def get_frame(self):
        if self.cap is None or self.frame is None:
            return None
        try:
            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]
        except Exception as e:
            print(f"⚠️ 图像处理错误: {e}")
            return None

    def release(self):
        self.running = False
        time.sleep(0.2)
        if self.cap is not None:
            self.cap.release()
        cv2.destroyAllWindows()

# get_image 将在main.py中初始化
get_image = None