[英]Implementing Kruskal's Algorithm in Python on images
A grid defines an image using edges stored in two arrays: 网格使用存储在两个数组中的边来定义图像:
h[x][y]
gives the edge weight from x,y
to x+1,y
h[x][y]
给出从x,y
到x+1,y
的边权重 v[x][y]
gives the edge weight from x,y
to x,y+1
v[x][y]
给出从x,y
到x,y+1
的边权重 I'm trying to implement Kruskal's algorithm. 我正在尝试实现Kruskal的算法。 This is fairly straightforward- I can find implementations online and copy them.
这非常简单 - 我可以在线找到实现并复制它们。 The issue is dealing with edges.
问题是处理边缘。 Specifically;
特别; sorting them is confusing.
对它们进行排序令人困惑。
Is there a better way to store the edges for this take specifically? 是否有更好的方法来存储这个特殊的边缘? I want them to be from every pixel to the adjacent pixels.
我希望它们从每个像素到相邻的像素。 I have the image stored as i[x][y], and the edge weight is just the difference between the image values.
我将图像存储为i [x] [y],边缘权重只是图像值之间的差异。
What you need to do is create a list of all the edges and then sort them. 您需要做的是创建所有边的列表,然后对它们进行排序。 To do this, you will need to define a class Edge:
为此,您需要定义一个类Edge:
class Edge:
def x
def y
def direction
def weight
Then, parse the h
and v
matrices and build up the edges
list. 然后,解析
h
和v
矩阵并构建edges
列表。 In the end, it should have 2 * N * M
elements. 最后,它应该有
2 * N * M
元素。 The direction of the edges should be either 'h'
or 'v'
, depending on the matrix that you parsed. 边缘的方向应为
'h'
或'v'
,具体取决于您解析的矩阵。
If you don't use the h
and v
matrices for any other purposes, you may drop them altogether, since you can compute the weights of the edges directly from the i
matrix. 如果您不将
h
和v
矩阵用于任何其他目的,则可以完全删除它们,因为您可以直接从i
矩阵计算边的权重。
Finally, for the purposes of the algorithm, you need to sort the list using the weight as a criterion: 最后,出于算法的目的,您需要使用权重作为标准对列表进行排序:
edges.sort(key=weight)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.