How to calculate dice coefficient for measuring accuracy of image segmentation in python

Please refer to Dice similarity coefficient at wiki

A sample code segment here for your reference. Please note that you need to replace k with your desired cluster since you are using k-means.

import numpy as np

k=1

# segmentation
seg = np.zeros((100,100), dtype='int')
seg[30:70, 30:70] = k

# ground truth
gt = np.zeros((100,100), dtype='int')
gt[30:70, 40:80] = k

dice = np.sum(seg[gt==k])*2.0 / (np.sum(seg) + np.sum(gt))

print 'Dice similarity score is {}'.format(dice)