scikit-image
64 строки · 1.8 Кб
1import networkx as nx
2import numpy as np
3from scipy import sparse
4from . import _ncut_cy
5
6
7def DW_matrices(graph):
8"""Returns the diagonal and weight matrices of a graph.
9
10Parameters
11----------
12graph : RAG
13A Region Adjacency Graph.
14
15Returns
16-------
17D : csc_matrix
18The diagonal matrix of the graph. ``D[i, i]`` is the sum of weights of
19all edges incident on `i`. All other entries are `0`.
20W : csc_matrix
21The weight matrix of the graph. ``W[i, j]`` is the weight of the edge
22joining `i` to `j`.
23"""
24# sparse.eighsh is most efficient with CSC-formatted input
25W = nx.to_scipy_sparse_array(graph, format='csc')
26entries = W.sum(axis=0)
27D = sparse.dia_matrix((entries, 0), shape=W.shape).tocsc()
28
29return D, W
30
31
32def ncut_cost(cut, D, W):
33"""Returns the N-cut cost of a bi-partition of a graph.
34
35Parameters
36----------
37cut : ndarray
38The mask for the nodes in the graph. Nodes corresponding to a `True`
39value are in one set.
40D : csc_matrix
41The diagonal matrix of the graph.
42W : csc_matrix
43The weight matrix of the graph.
44
45Returns
46-------
47cost : float
48The cost of performing the N-cut.
49
50References
51----------
52.. [1] Normalized Cuts and Image Segmentation, Jianbo Shi and
53Jitendra Malik, IEEE Transactions on Pattern Analysis and Machine
54Intelligence, Page 889, Equation 2.
55"""
56cut = np.array(cut)
57cut_cost = _ncut_cy.cut_cost(cut, W.data, W.indices, W.indptr, num_cols=W.shape[0])
58
59# D has elements only along the diagonal, one per node, so we can directly
60# index the data attribute with cut.
61assoc_a = D.data[cut].sum()
62assoc_b = D.data[~cut].sum()
63
64return (cut_cost / assoc_a) + (cut_cost / assoc_b)
65