Skip to content

Instantly share code, notes, and snippets.

@brunodoamaral
Forked from JDWarner/_dice.py
Last active March 16, 2024 18:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save brunodoamaral/e130b4e97aa4ebc468225b7ce39b3137 to your computer and use it in GitHub Desktop.
Save brunodoamaral/e130b4e97aa4ebc468225b7ce39b3137 to your computer and use it in GitHub Desktop.
Dice coefficient between two boolean NumPy arrays or array-like data. This is commonly used as a set similarity measurement (though note it is not a true metric; it does not satisfy the triangle inequality). The dimensionality of the input is completely arbitrary, but `im1.shape` and `im2.shape` much be equal. This Gist is licensed under the mod…
def dice(im1, im2, empty_score=1.0):
"""
Computes the Dice coefficient, a measure of set similarity.
Parameters
----------
im1 : array-like, bool
Any array of arbitrary size. If not boolean, will be converted.
im2 : array-like, bool
Any other array of identical size. If not boolean, will be converted.
Returns
-------
dice : float
Dice coefficient as a float on range [0,1].
Maximum similarity = 1
No similarity = 0
Both are empty (sum eq to zero) = empty_score
Notes
-----
The order of inputs for `dice` is irrelevant. The result will be
identical if `im1` and `im2` are switched.
"""
im1 = np.asarray(im1).astype(np.bool)
im2 = np.asarray(im2).astype(np.bool)
if im1.shape != im2.shape:
raise ValueError("Shape mismatch: im1 and im2 must have the same shape.")
im_sum = im1.sum() + im2.sum()
if im_sum == 0:
return empty_score
# Compute Dice coefficient
intersection = np.logical_and(im1, im2)
return 2. * intersection.sum() / im_sum
@MaleehaKhan
Copy link

my images are in bmp format, I have this error
at line
File "work.py", line 29, in dice
im1 = np.asarray(im1).astype(np.bool)
ValueError: invalid literal for int() with base 10

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment