Skip to content

Commit

Permalink
ENH: Select foreground mask in otsu
Browse files Browse the repository at this point in the history
Otsu thresholding would often assign the mask value to the background of
the image, rather than the object within the image.

This commit looks at the corner (0,0,0) pixel in the otsu mask, and if
it isn't 0, swaps the otsu mask values so that it is zero.

This assumes the 0,0,0 pixel should be the background in the maask.
  • Loading branch information
aylward committed Jul 14, 2024
1 parent 2096e22 commit 2f837b4
Showing 1 changed file with 24 additions and 3 deletions.
27 changes: 24 additions & 3 deletions src/minder3d/lib/sovOtsuLogic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,35 @@


class OtsuLogic:
def fix_mask(self, mask_img):
mask_arr = itk.GetArrayFromImage(mask_img)
mask_values = np.unique(mask_arr)

new_mask_arr = mask_arr.copy()

for i in range(len(mask_values)):
indexes = np.where(mask_arr == mask_values[i])
new_mask_arr[indexes] = i
corner_value = new_mask_arr[0, 0, 0]
if corner_value != 0:
indexes_wrong_bg = np.where(new_mask_arr == 0)
indexes_wrong_fg = np.where(new_mask_arr == corner_value)
new_mask_arr[indexes_wrong_bg] = corner_value
new_mask_arr[indexes_wrong_fg] = 0

new_img = itk.GetImageFromArray(new_mask_arr)
new_img.CopyInformation(mask_img)

return new_img

def run(self, inputImage, numberOfThresholds):
if numberOfThresholds <= 1:
filter = itk.OtsuThresholdImageFilter.New(Input=inputImage)
filter.Update()
return filter.GetOutput().astype(np.uint8)
return self.fix_mask(filter.GetOutput().astype(np.uint8))
else:
filter = itk.OtsuMultipleThresholdsImageFilter.New(Input=inputImage)
filter.SetNumberOfThresholds(numberOfThresholds)
filter.Update()
img = filter.GetOutput().astype(np.uint8)
return img

return self.fix_mask(filter.GetOutput().astype(np.uint8))

0 comments on commit 2f837b4

Please sign in to comment.