python - 在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)]
解决方案
这里的想法是通过构造一个键使用字典对图像进行分组。如果我考虑图像的描绘方式,我可以认为坐标围绕 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)]]
推荐阅读
- mariadb - brew install mariadb 失败,因为系统无法 chown for auth_pam_tool
- reactjs - 将 Photo Sphere Viewer 与 React 一起使用
- excel - 如何为每次另一列的值更改时重置的行提供数字?
- oauth - Autodesk-forge 查看器:访问令牌
- java - 如何使用命令提示符运行包含 python 文件的 java jar
- java - ClimaCell API json 转换为 POJO
- c++ - C++无效使用非静态成员函数?
- python - 为特定日期创建具有给定动态公司名称的数据框
- java - 如何将计划任务分配给特定线程?
- c# - 在 Asp.Net Core 中使用 Swagger 在请求中未发送授权承载令牌