-
Notifications
You must be signed in to change notification settings - Fork 3
/
parsing.py
72 lines (53 loc) · 1.87 KB
/
parsing.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
"""Parsing code for DICOMS and contour files"""
import dicom
from dicom.errors import InvalidDicomError
import numpy as np
from PIL import Image, ImageDraw
def parse_contour_file(filename):
"""Parse the given contour filename
:param filename: filepath to the contourfile to parse
:return: list of tuples holding x, y coordinates of the contour
"""
coords_lst = []
with open(filename, 'r') as infile:
for line in infile:
coords = line.strip().split()
x_coord = float(coords[0])
y_coord = float(coords[1])
coords_lst.append((x_coord, y_coord))
return coords_lst
def parse_dicom_file(filename):
"""Parse the given DICOM filename
:param filename: filepath to the DICOM file to parse
:return: dictionary with DICOM image data
"""
try:
dcm = dicom.read_file(filename)
dcm_image = dcm.pixel_array
try:
intercept = dcm.RescaleIntercept
except AttributeError:
intercept = 0.0
try:
slope = dcm.RescaleSlope
except AttributeError:
slope = 0.0
if intercept != 0.0 and slope != 0.0:
dcm_image = dcm_image*slope + intercept
dcm_dict = {'pixel_data' : dcm_image, 'dicom' : dcm}
return dcm_dict
except InvalidDicomError:
return None
def poly_to_mask(polygon, width, height):
"""Convert polygon to mask
:param polygon: list of pairs of x, y coords [(x1, y1), (x2, y2), ...]
in units of pixels
:param width: scalar image width
:param height: scalar image height
:return: Boolean mask of shape (height, width)
"""
# http://stackoverflow.com/a/3732128/1410871
img = Image.new(mode='L', size=(width, height), color=0)
ImageDraw.Draw(img).polygon(xy=polygon, outline=0, fill=1)
mask = np.array(img).astype(bool)
return mask