Skip to content

Instantly share code, notes, and snippets.

@gireeshkbogu
Created April 5, 2020 13:41
Show Gist options
  • Save gireeshkbogu/95106c6b246f1bb9625c1e1e020cb309 to your computer and use it in GitHub Desktop.
Save gireeshkbogu/95106c6b246f1bb9625c1e1e020cb309 to your computer and use it in GitHub Desktop.
Changes the unordered class names of multiple image masks in a give folder
import sys
import os
from PIL import Image
import shutil
import numpy as np
mask_dir = "/Users/gireeshbogu/Downloads/MSNYD_8_22_17/MSNYD_8_22_17__AB_AXT1_fl2d_inopp_mbh_15/masks_machine/"
new_mask_dir = "/Users/gireeshbogu/Downloads/MSNYD_8_22_17__AB_AXT1_fl2d_inopp_mbh_15_masks/"
if not os.path.exists(new_mask_dir):
os.mkdir(new_mask_dir)
for filename in os.scandir(mask_dir):
if filename.path.endswith(".png"):
image = Image.open(filename.path)
mask = np.array(image)
mask[mask==3] = 50, #Right_Rectus_Abdominis
mask[mask==4] = 51, #Left_Rectus_Abdominis
mask[mask==5] = 52, #Right_Psoas
mask[mask==6] = 53, #Left_Psoas
mask[mask==7] = 54, #Right_Erector_Spinae
mask[mask==8] = 55, #Left_Erector_Spinae
mask[mask<50] = 0, #unlabeled
mask[mask==50] = 1, #Right_Rectus_Abdominis
mask[mask==51] = 2, #Left_Rectus_Abdominis
mask[mask==52] = 3, #Right_Psoas
mask[mask==53] = 4, #Left_Psoas
mask[mask==54] = 5, #Right_Erector_Spinae
mask[mask==55] = 6 #Left_Erector_Spinae
masked_img = Image.fromarray(mask)
new_img_path = os.path.join(new_mask_dir, filename.name)
masked_img.save(new_img_path)
@gireeshkbogu
Copy link
Author

gireeshkbogu commented Apr 5, 2020

You can test the output using the following.

from PIL import Image
import sys
import numpy as np

original_mask = Image.open("/Users/gireeshbogu/Downloads/MSNYD_8_22_17/MSNYD_8_22_17__AB_AXT1_fl2d_inopp_mbh_15/masks_machine/IM-0010-0008.png")

array = np.array(original_mask)
#print('Array Dimensions', array.shape)
new_array = [tuple(row) for row in array]
uniques = np.unique(new_array)
print(uniques)

modified_mask = Image.open("MSNYD_8_22_17__AB_AXT1_fl2d_inopp_mbh_15_masks/IM-0010-0008.png")

array = np.array(modified_mask)
new_array = [tuple(row) for row in array]
uniques = np.unique(new_array)
print(uniques)

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