Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用循环多变量?_Python_Opencv_Yolov5 - Fatal编程技术网

Python 如何使用循环多变量?

Python 如何使用循环多变量?,python,opencv,yolov5,Python,Opencv,Yolov5,我用的是Yolov5。我想更换我的网络摄像头->兰开米拉 class LoadStreams: # multiple IP or RTSP cameras def __init__(self, sources='streams.txt', img_size=640): self.mode = 'images' self.img_size = img_size if os.path.isfile(sources): with open(sources,

我用的是Yolov5。我想更换我的网络摄像头->兰开米拉

class LoadStreams:  # multiple IP or RTSP cameras
def __init__(self, sources='streams.txt', img_size=640):
    self.mode = 'images'
    self.img_size = img_size

    if os.path.isfile(sources):
        with open(sources, 'r') as f:
            sources = [x.strip() for x in f.read().splitlines() if len(x.strip())]
    else:
        sources = [sources]
        

    n = len(sources)
    self.imgs = [None] * n
    self.sources = sources
    for i, s in enumerate(sources):
        # Start the thread to read frames from the video stream
        print('%g/%g: %s... ' % (i + 1, n, s), end='')
        cap = cv2.VideoCapture(eval(s) if s.isnumeric() else s)
        assert cap.isOpened(), 'Failed to open %s' % s
        w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        fps = cap.get(cv2.CAP_PROP_FPS) % 100
        _, self.imgs[i] = cap.read()  # guarantee first frame
        thread = Thread(target=self.update, args=([i, cap]), daemon=True)
        print(' success (%gx%g at %.2f FPS).' % (w, h, fps))
        thread.start()
    print('')  # newline

    # check for common shapes
    s = np.stack([letterbox(x, new_shape=self.img_size)[0].shape for x in self.imgs], 0)  # inference shapes
    self.rect = np.unique(s, axis=0).shape[0] == 1  # rect inference if all shapes equal
    if not self.rect:
        print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')

def update(self, index, cap):
    # Read next stream frame in a daemon thread
    n = 0
    while cap.isOpened():
        n += 1
        # _, self.imgs[index] = cap.read()
        cap.grab()
        if n == 4:  # read every 4th frame
            _, self.imgs[index] = cap.retrieve()
            n = 0
        time.sleep(0.01)  # wait time

def __iter__(self):
    self.count = -1
    return self

def __next__(self):
    self.count += 1
    img0 = self.imgs.copy()
    if cv2.waitKey(1) == ord('q'):  # q to quit
        cv2.destroyAllWindows()
        raise StopIteration

    # Letterbox
    img = [letterbox(x, new_shape=self.img_size, auto=self.rect)[0] for x in img0]

    # Stack
    img = np.stack(img, 0)

    # Convert
    img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)  # BGR to RGB, to bsx3x416x416
    img = np.ascontiguousarray(img)

    return self.sources, img, img0, None

def __len__(self):
    return 0  # 1E12 frames = 32 streams at 30 FPS for 30 years
此代码返回“self.sources,img,img0,None”

if webcam:
    view_img = True
    cudnn.benchmark = True  # set True to speed up constant image size inference
    dataset = LoadStreams(source, img_size=imgsz)
    print((dataset))
我使用“数据集”

 for path, img, im0s, vid_cap in dataset:
    img = torch.from_numpy(img).to(device)
    img = img.half() if half else img.float()  # uint8 to fp16/32
    img /= 255.0  # 0 - 255 to 0.0 - 1.0
如何对数据集中的路径、img、im0s、vid_cap使用

我的兰卡姆密码

def livecame():
vimba = Vimba()
vimba.startup()
system = vimba.system()

system.run_feature_command("GeVDiscoveryAllOnce")
time.sleep(0.1)

camera_ids = vimba.camera_ids()

# for cam_id in camera_ids:
#     print("Camera found: ", cam_id)

print(camera_ids[0])
c0 = vimba.camera(camera_ids[0])
c0.open()

pixel_format = c0.feature("PixelFormat")
pixel_format.value = "BayerBG8"
try:
    c0.StreamBytesPerSecond = 100000000
except:
    pass

frame = c0.new_frame()
frame.announce()

c0.start_capture()

try:
    frame.queue_for_capture()
    success = True
except:
    success = False

c0.run_feature_command("AcquisitionStart")
c0.run_feature_command("AcquisitionStop")
frame.wait_for_capture(1000)
frame_data = frame.buffer_data()

k = cv2.waitKey(1)

if k == 0x1b:
    cv2.destroyAllWindows()

if success:
    img = np.ndarray(buffer=frame_data,
                    dtype=np.uint8,
                    shape=(frame.data.height, frame.data.width, 1))
    img = cv2.cvtColor(img, cv2.COLOR_BAYER_BG2RGB)
    img0 = img.copy()
    img = img.tolist()
    img = [letterbox(x, new_shape=(800,400), auto= True)[0] for x in img0]
    #img = np.ascontiguousarray(img)
    img = np.stack(img, 0)
    #img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)  # BGR to RGB, to bsx3x416x416
    img = np.ascontiguousarray(img)
    
return ['0'], img, img0
但我使用的是
dataset=new\u file.livecome()

我可以看到错误值错误:没有足够的值来解包(预期为3,得到1)

对于路径、img、im0s,数据集中的vid_cap:


如何使用多个变量?在for循环中?

在Python OpenCV中,一种方法就是简单地使用zip

for component in zip(contours, hierarchy):
    cntr = component[0]
    hier = component[1]