CellPilot / MTdata /data_analysis /MoNuSeg_mask.py
philippendres's picture
Upload folder using huggingface_hub
907462b verified
Raw
History Blame Contribute Delete
1.59 kB
import numpy as np
from xml.dom import minidom
from skimage.draw import polygon
from tifffile import imread
def he_to_binary_mask(filename):
im_file = "../../data/MoNuSeg/MoNuSeg 2018 Training Data/Tissue Images/" + filename + '.tif'
xml_file = "../../data/MoNuSeg/MoNuSeg 2018 Training Data/Annotations/" + filename + '.xml'
# Parse the XML file
xDoc = minidom.parse(xml_file)
Regions = xDoc.getElementsByTagName('Region')
xy = []
for regioni in range(Regions.length):
Region = Regions.item(regioni)
verticies = Region.getElementsByTagName('Vertex')
xy_region = np.zeros((verticies.length, 2))
for vertexi in range(verticies.length):
x = float(verticies.item(vertexi).getAttribute('X'))
y = float(verticies.item(vertexi).getAttribute('Y'))
xy_region[vertexi] = [x, y]
xy.append(xy_region)
arr = imread(im_file)
# Get image information
im_info = {
'Height': arr.shape[0],
'Width': arr.shape[1]
}
binary_mask = np.zeros((im_info['Height'], im_info['Width']))
color_mask = np.zeros((im_info['Height'], im_info['Width'], 3))
for zz, region in enumerate(xy):
print(f'Processing object # {zz + 1}')
smaller_x = region[:, 0]
smaller_y = region[:, 1]
# Create binary and color masks
polygon_mask = polygon(smaller_y, smaller_x, (im_info['Height'], im_info['Width']))
binary_mask[polygon_mask] += zz + 1
color_mask[polygon_mask] += np.random.rand(3)
return binary_mask, color_mask