首页 > 解决方案 > 在python中对等价的图片进行分组

问题描述

我有几张图片描绘了几个点的坐标(通常是 3-10 个点)。我想对具有相同点排列的图片进行分组。通过向量 (0, 1) 移动 (a),其中集合 (a) 的 3 个点具有坐标 (1, 1) (2, 1) 和 (3, 1),我们得到集合 (d) 具有 ( 1, 2) (2, 2) 和 (3, 2) 分别。类似地,在移动了一个向量(2, 0)之后,集合(a)变成了(1, 3)、(2, 3)和(3, 3)的集合(g)。然后我们可以将具有相同排列的集合(a),(d)和(g)分组并认为是等价的。你能帮帮我吗?

def is_shift(set1, set2): 
    shift = None  # will store a tuple of delta_x, delta_y
    for (x1, y1), (x2, y2) in zip(set1, set2): 
        cur_shift = x1 - x1, y1 - y2 
        if not shift:  # the first pair of points
            shift = cur_shift 
        elif shift != cur_shift: # shifted the same way as the first one?
            return False 
    return True 

matrices = array([
    [(1, 1), (2, 1), (3, 1)],
    [(1, 2), (2, 1), (3, 1)],
    [(1, 3), (2, 1), (2, 2)], 
    [(1, 2), (2, 2), (3, 2)], 
    [(1, 3), (2, 2), (3, 2)], 
    [(2, 3), (3, 1), (3, 2)],
    [(1, 3), (2, 3), (3, 3)], 
    [(2, 2), (3, 1), (4, 4)],
    ])

输出:

[[(1, 1), (2, 1), (3, 1)], [(1, 2), (2, 2), (3, 2)], [(1, 3), (2, 3), (3, 3)]]
[[(1, 2), (2, 1), (3, 1)], [(1, 3), (2, 2), (3, 2)]]
[[(1, 3), (2, 1), (2, 2)], [(2, 3), (3, 1), (3, 2)]]
[(2, 2), (3, 1), (4, 4)]

在此处输入图像描述

标签: pythonnumpy

解决方案


这里的想法是通过构造一个键使用字典对图像进行分组。如果我考虑图像的描绘方式,我可以认为坐标围绕 x 轴和 y 轴的偏移对于相似图像是相似的,如果我认为偏移为[x - min(x_coords) for x in x_coords][y - min(y_coords) for y in y_coords]

例如,对于图像 1x_coords = [1,2,3]y_coords = [2,2,2],位移将为(0, 1, 2)和 ,0,0,0因为 x 和 y 坐标的最小值分别为 1 和 2。这些移位的组合现在可以用作对不同图像进行分组的关键,如下所示

import collections

def group_matrices():

    matrices = [
        [(1, 1), (2, 1), (3, 1)],
        [(1, 2), (2, 1), (3, 1)],
        [(1, 3), (2, 1), (2, 2)],
        [(1, 2), (2, 2), (3, 2)],
        [(1, 3), (2, 2), (3, 2)],
        [(2, 3), (3, 1), (3, 2)],
        [(1, 3), (2, 3), (3, 3)],
        [(2, 2), (3, 1), (4, 4)],
    ]

    # Dictionary to group images
    groups = collections.defaultdict(list)

    # Iterate over the matrices
    for image in matrices:

        # Extract x and y coordinates from the image
        x_coords, y_coords = zip(*image)

        # Compute minimum of x and y coordinates
        min_x = min(x_coords)
        min_y = min(y_coords)

        # Compute the shifts
        key_x = tuple(x - min_x for x in x_coords)
        key_y = tuple(y - min_y for y in y_coords)

        # Create the key combining the shifts and add image
        # to corresponding key
        key = (key_x, key_y)
        groups[key].append(image)

    # Return the list of lists of grouped images
    return [value for value in groups.values()]

for group in group_matrices():
    print(group)

输出将是

[[(1, 1), (2, 1), (3, 1)], [(1, 2), (2, 2), (3, 2)], [(1, 3), (2, 3), (3, 3)]]
[[(1, 2), (2, 1), (3, 1)], [(1, 3), (2, 2), (3, 2)]]
[[(1, 3), (2, 1), (2, 2)], [(2, 3), (3, 1), (3, 2)]]
[[(2, 2), (3, 1), (4, 4)]]

推荐阅读