0

我正在使用 cv2 逐帧分析视频,如果帧号在某些时间戳之间,我想将帧保存为 1,如果不是,则保存为 0。我有两个列表,一个是开始时间,一个是结束时间:

start_times = [0, 10, 15]
end_times = [2, 12, 17]

我想将帧号 0,1,2 和 10,11,12 和 15,16,17 的帧保存为 1,其他帧保存为 0。

我的代码将正确的帧保存为 1,但将不需要的帧保存为 0,因为我使用的是 for 循环。请参见下面的简化示例:

start_times = [0,10,15]
end_times = [2,12,17]

currentframe = 0

while True: 
    try:
        for index,time in enumerate(start_times):
            if start_times[index] <= currentframe <= end_times[index]:
                print('save images as 1')
            else:
                print('save images as 0')
        currentframe += 1

        if currentframe == 20:
            break

    except IndexError:
        break

第一帧的输出:

save images as 1
save images as 0
save images as 0

如何更改我的代码以使第一帧仅保存为 1?

4

3 回答 3

1

我不确定我是否清楚地理解了你,但试试这个并告诉我它是否是你想要的:

start_times = [0,10,15]
end_times = [2,12,17]

times = sorted(start_times + end_times)
print(times)

i = 0
while i + 1 < len(times):
  k = times[i]
  while k <= times[i + 1]:
    if i % 2 == 0:
      print('save [frame {}] as 1'.format(k))
    else:
      print('save [frame {}] as 0'.format(k))    
    k += 1
  i += 1
于 2020-11-20T09:21:51.957 回答
0

我的一个朋友通过使用范围给了我解决方案:

current_frame = 0
start_times = [0, 10, 15]
end_times = [2, 12, 17]
ranges = [range(start, stop) for start, stop in zip(start_times, end_times)]

while True:
    if any([current_frame in my_range for my_range in ranges]):
        print('save image as 1')
    else:
        print('save image as 0')
...

于 2020-11-20T09:35:18.387 回答
0

我想这就是你要找的吗?

while curr_frame < 20:
    is_in = any(filter(lambda start_end: start_end[0] <= curr_frame <= start_end[1],
                       zip(start_times, end_times))))
    print(f'Save image as {int(is_in)}')
    curr_frame += is_in
于 2020-11-20T09:12:59.373 回答