#NEWLINE# def _calc_adjacency_matrix( label_img , n_region ) : #NEWLINE# #INDENT# r = numpy . vstack ( [ label_img [ : , : ( - 1 ) ] . ravel ( ) , label_img [ : , 1 : ] . ravel ( ) ] ) #NEWLINE# b = numpy . vstack ( [ label_img [ : ( - 1 ) , : ] . ravel ( ) , label_img [ 1 : , : ] . ravel ( ) ] ) #NEWLINE# t = numpy . hstack ( [ r , b ] ) #NEWLINE# A = scipy . sparse . coo_matrix ( ( numpy . ones ( t . shape [ 1 ] ) , ( t [ 0 ] , t [ 1 ] ) ) , shape = ( n_region , n_region ) , dtype = bool ) . todense ( ) . getA ( ) #NEWLINE# A = ( A | A . transpose ( ) ) #NEWLINE# for i in range ( n_region ) : #NEWLINE# #INDENT# A [ ( i , i ) ] = True #NEWLINE# #UNINDENT# dic = { i : ( { i } ^ set ( numpy . flatnonzero ( A [ i ] ) ) ) for i in range ( n_region ) } #NEWLINE# Adjacency = collections . namedtuple ( 'Adjacency' , [ 'matrix' , 'dictionary' ] ) #NEWLINE# return Adjacency ( matrix = A , dictionary = dic )