Commit d6bbed61 by Jiri Borovec

refactoring and add basic show unary costs

parent 44efb410
__author__ = 'Jiri Borovec'
import os, sys
import numpy as np
import logging
logger = logging.getLogger(__name__)
def convertWeightsBinary2indexes (weights) :
logger.debug('convert binary weights {} to list of indexes with True'.format(weights.shape))
# if type(weights)==np.ndarray : weights = weights.tolist()
weighIdx = [None] * weights.shape[0]
for i in range(weights.shape[0]) :
# find postions equal 1
# vec = [j for j in range(weights.shape[1]) if weights[i,j]==1]
vec = np.where(weights[i, :] == 1)[0]
weighIdx[i] = vec +1
# idxs = np.where(weights == 1)
# for i in range(weights.shape[0]) :
# weighIdx[i] = idxs[1][idxs[0]==i] +1
return weighIdx
def weighsImageByAtlas_overlapMajor (img, atlas) :
# logger.debug('weights input image according given atlas')
weights = weighsImageByAtlas_overlapTreshold(img, atlas, 0.5)
return weights
def weighsImageByAtlas_overlapPartial (img, atlas) :
# logger.debug('weights input image according given atlas')
lbs = np.unique(atlas).tolist()
weights = weighsImageByAtlas_overlapTreshold(img, atlas, (1. / len(lbs)))
return weights
def weighsImageByAtlas_overlapTreshold (img, atlas, thr=0.5) :
# logger.debug('weights input image according given atlas')
# simple weight
lbs = np.unique(atlas).tolist()
# logger.debug('weights image by atlas with labels: {}'.format(lbs))
if 0 in lbs : lbs.remove (0)
weight = [0] * np.max(lbs)
for l in lbs :
equal = np.sum( img[atlas==l] )
total = np.sum( atlas==l )
score = equal / float(total)
if score >= thr :
weight[l-1] = 1
return weight
def fillEmptyPatterns (binWeighs) :
sums = np.sum(binWeighs, axis=0)
logger.debug('IN > sum over weights: {}'.format(sums))
for i, v in enumerate(sums) :
if v == 0 :
binWeighs[:, i] = 1
logger.debug('OUT < sum over weights: {}'.format(np.sum(binWeighs, axis=0)))
return binWeighs
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
logger.info('DONE')
\ No newline at end of file
__author__ = 'Jiri Borovec'
import os, sys
import numpy as np
from sklearn import metrics
import logging
logger = logging.getLogger(__name__)
def compareAtlas_randomPositions (A1, A2) :
logger.debug('comparing two atlases of shapes {} <-> {}'.format(A1.shape, A2.shape))
assert np.array_equal(A1.shape, A2.shape)
# assert A1.shape[0]==A2.shape[0] and A1.shape[1]==A2.shape[1]
logger.debug('unique labels are {} and {}'.format(np.unique(A1).tolist(), np.unique(A2).tolist()))
X, Y = np.meshgrid(range(A1.shape[0]), range(A1.shape[1]))
vecX, vecY = X.flatten(), Y.flatten()
vecX_perm = np.random.permutation(vecX)
vecY_perm = np.random.permutation(vecY)
diffs = 0
for x1, y1, x2, y2 in zip(vecX, vecY, vecX_perm, vecY_perm) :
b1 = A1[x1,y1] == A1[x2,y2]
b2 = A2[x1,y1] == A2[x2,y2]
if not b1 == b2 : # T&F or F&T
# logger.debug('coords [{},{}], [{},{}] gives vals: {}, {}'.format(x1, y1, x2, y2, b1, b2))
# logger.debug('diff: {}?={} and {}?={}'.format(A1[x1,y1], A1[x2,y2], A2[x1,y1], A2[x2,y2]))
diffs += 1
res = diffs / float(len(vecX))
return res
# Rand index, o tom uz jsme mluvili.
# Ted jde jen o to, jak tento index vypocitat efektivne. Coz, kdyz si
# rozmyslite, neni prilis tezke: udelate kontingencni tabulku=histogram, tedy oznacime n_ij kolik pixelu na stejnych
# souradnicich patri do tridy 'i'v prvnim obrazku a do tridy 'j' v druhem. Pak pocet shod (dva prvky jsou ve strejne
# tride v prvnim obrazku a ve stejne tride v druhem, nebo jsou v ruznych tridach v prvnim i v druhem) lze vyjadrit
# z histogramu - viz vzorec (1), clanek http://link.springer.com/article/10.1007%2FBF01908075
#
# Existuje i Adjusted Random Index, viz stejny clanek, nebo taky https://en.wikipedia.org/wiki/Rand_index
# Pro nase ucely je to asi jedno, proto budeme chtit jen porovnavat metody mezi sebou.
def compareAtlas_adjustedRand (A1, A2) :
assert np.array_equal(A1.shape, A2.shape)
ars = metrics.adjusted_rand_score(A1.ravel(), A2.ravel())
res = 0.5 - (ars / 2.)
return res
def overlapMatrixMultilabelSegm (seg1, seg2) :
logger.debug('computing overlap of two segm of shapes {} <-> {}'.format(seg1.shape, seg2.shape))
assert np.array_equal(seg1.shape, seg2.shape)
uLb1 = np.unique(seg1)
uLb2 = np.unique(seg2)
uLb1 = dict(zip(uLb1,range(len(uLb1))))
uLb2 = dict(zip(uLb2,range(len(uLb2))))
logger.debug('unique labels:\n {}\n {}'.format(uLb1, uLb2))
res = np.zeros([len(uLb1), len(uLb2)])
for i in range(seg1.shape[0]) :
for j in range(seg1.shape[1]) :
u1, u2 = uLb1[seg1[i, j]], uLb2[seg2[i, j]]
res[u1, u2] += 1
res[u2, u1] += 1
# logger.debug(res)
return res
def compareMatrices (M1, M2) :
assert np.array_equal(M1.shape, M2.shape)
diff = np.sum(abs(M1 - M2))
return diff / float(np.product(M1.shape))
def compareWeights (C1, C2) :
return compareMatrices(C1, C2)
def test_Atlases () :
logger.info('testing METRIC')
A = np.random.randint(0,4, (5,5))
A2 = A.copy()
A2[A2==0] = -1
B = np.random.randint(0,4, (5,5))
logger.debug('compareAtlas_randomPositions, A <-> A: {}'.format(compareAtlas_randomPositions(A,A2)))
logger.debug('compareAtlas_randomPositions, A <-> B: {}'.format(compareAtlas_randomPositions(A,B)))
logger.debug('compareAtlas_adjustedRand, A <-> A: {}'.format(compareAtlas_adjustedRand(A,A2)))
logger.debug('compareAtlas_adjustedRand, A <-> B: {}'.format(compareAtlas_adjustedRand(A,B)))
return None
if __name__ == "__main__":
logging.basicConfig(level=logging.DEBUG)
test_Atlases()
logger.info('DONE')
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment