如何使用for循环许多变量?

Posted

技术标签:

【中文标题】如何使用for循环许多变量?【英文标题】:How use for loop many variable? 【发布时间】:2021-03-12 23:13:29 【问题描述】:

我正在使用 Yolov5。我想更换我的网络摄像头 -> lancamera

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

for path, img, im0s, vid_cap in dataset:怎么用??

我的 lancam 代码

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_file.livecame()

我可以看到错误 ValueError: not enough values to unpack (expected 3, got 1)

in for path, img, im0s, vid_cap in dataset:

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

【问题讨论】:

【参考方案1】:

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

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

【讨论】:

以上是关于如何使用for循环许多变量?的主要内容,如果未能解决你的问题,请参考以下文章

如何使用“for”循环创建变量名? [复制]

我如何在 for 循环外使用 for 循环范围变量形式?

如何在bash for循环中使用变量[重复]

如何使用'for'循环将新变量传递给python脚本

js 如何保存循环内的变量,然后循环外使用这个变量?

如何使用 DJango 在 for 循环中使用变量