Implementing Kruskal's Algorithm in Python on Images
The mesh defines the image using the edges stored in two arrays:
-
h[x][y]
gives the weight of the edge fromx,y
tox+1,y
-
v[x][y]
gives the weight of the rib fromx,y
tox,y+1
I am trying to implement Kruskal's algorithm. It's pretty simple - I can find implementations on the internet and copy them. The problem is with the ribs. In particular, sorting them is confusing.
Is there a better way to store edges for this? I want them from every pixel to adjacent pixels. I have an image saved as i [x] [y] and the edge weight is just the difference between the image values.
source to share
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 the Edge class:
class Edge:
def x
def y
def direction
def weight
Then we analyze the matrices h
and v
and create a list edges
. After all, it must have elements 2 * N * M
. The direction of the edges should be either 'h'
or 'v'
, depending on the matrix being analyzed.
If you do not use a matrix h
, and v
for any other purposes, you can opt out of them altogether, so how can you calculate the weights of the edges directly from the matrix i
.
Finally, for the purposes of the algorithm, you need to sort the list using weight as a criterion:
edges.sort(key=weight)
source to share