按时间间隔分组图像 python

2024-04-19 16:19:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个脚本,从图像中取出exif数据,放到列表中,然后对列表进行排序,这就是我的列表,第一个位置是以秒为单位的图像时间,第二个位置是图像路径,我的列表

[[32372, 'F:\rubish\VOL1\cam\G0013025.JPG'], [32373, 'F:\rubish\VOL1\cam\G0013026.JPG'], [32373, 'F:\rubish\VOL1\cam\G0013027.JPG'],.... etc etc etc

用@blhsing编写的一个脚本对我的图像进行分组,效果很好,但是我想开始分组,而不是从第一个图像开始,按给定的位置进行分组 这是一个脚本:

groups = []
for r in img:
    if groups and r[0] - groups[-1][-1][0] <= 5:
        groups[-1].append(r)
    else:
        groups.append([r])
for g in groups:
    print(g[0][1], g[0][0], g[-1][0], g[-1][1])

而我所拥有的,它不好用,它只拍一张图片,不创建一个组,有人能帮我修复它吗??你知道吗

groups = []
print(iii, "iii")
#print(min_list, " my min list ")
img.sort()
cnt = 0
mili = [32372, 34880]

for n in min_list:
    #print(n, "mili")
    for i in img:
        #print(i[0])
        if n == i[0]:
            if groups and i[0] - groups[-1][-1][0] <= 5:
                groups[-1].append(i)
            else:
                groups.append([i])
    for ii in groups:
        print(ii[0][1], ii[0][0], ii[-1][0], ii[-1][1])

在这里,我有我的minu列表和2个位置意味着我只想创建2个组,和分类器只从这2个位置开始的图像,间隔5秒之前。你知道吗


Tags: in图像脚本列表imgforetcii
2条回答

当然!我前几天也写了同样的算法,但是是针对JavaScript的。易于移植到Python。。。你知道吗

import pprint

def group_seq(data, predicate):
    groups = []
    current_group = None
    for datum in data:
        if current_group:
            if not predicate(current_group[-1], datum):  # Abandon the group
                current_group = None
        if not current_group:  # Need to start a new group
            current_group = []
            groups.append(current_group)
        current_group.append(datum)
    return groups


data = [
    [32372, r'F:\rubish\VOL1\cam\G0013025.JPG'],
    [32373, r'F:\rubish\VOL1\cam\G0013026.JPG'],
    [32373, r'F:\rubish\VOL1\cam\G0013027.JPG'],
    [32380, r'F:\rubish\VOL1\cam\G0064646.JPG'],
    [32381, r'F:\rubish\VOL1\cam\G0064646.JPG'],
]

groups = group_seq(
    data=data,
    predicate=lambda a, b: abs(a[0] - b[0]) > 5,
)

pprint.pprint(groups)

输出

[[[32372, 'F:\\rubish\\VOL1\\cam\\G0013025.JPG'],
  [32373, 'F:\\rubish\\VOL1\\cam\\G0013026.JPG'],
  [32373, 'F:\\rubish\\VOL1\\cam\\G0013027.JPG']],
 [[32380, 'F:\\rubish\\VOL1\\cam\\G0064646.JPG'],
  [32381, 'F:\\rubish\\VOL1\\cam\\G0064646.JPG']]]

基本上,predicate是一个函数,如果ba属于同一个组,那么它应该返回True;对于您的用例,我们查看元组/列表中第一个项的(绝对)差异,即时间戳。你知道吗

由于您的img列表已经按时间排序,因此如果与最后一个条目的时间差不超过5秒,您可以遍历记录并将它们附加到输出列表的最后一个子列表(在我的示例代码中称为groups),否则将记录放入输出列表的新子列表中。请记住,在Python中,-1的下标表示列表中的最后一项。你知道吗

groups = []
for r in img:
    if groups and r[0] - groups[-1][-1][0] <= 5:
        groups[-1].append(r)
    else:
        groups.append([r])
for g in groups:
    print(g[0][1], g[0][0], g[-1][0], g[-1][1])

相关问题 更多 >