Skip to content

Commit

Permalink
fixed the mpr calc issue
Browse files Browse the repository at this point in the history
  • Loading branch information
zemmyang committed Apr 5, 2022
1 parent 7c175ff commit d63d5b3
Show file tree
Hide file tree
Showing 15 changed files with 135 additions and 117 deletions.
9 changes: 0 additions & 9 deletions MRICenterline/app/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +0,0 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
documentation
"""

if __name__ == '__main__':
pass
5 changes: 4 additions & 1 deletion MRICenterline/app/database/load_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@ def read_points(pt_id, status: PointStatus, image_properties):
con.close()

for pt in points:
point = Point.point_from_physical(pt, image_properties)
if CFG.get_testing_status("use-slice-location"):
point = Point.point_from_vtk_coords(pt, image_properties)
else:
point = Point.point_from_physical(pt, image_properties)
out_array.add_point(point)

return out_array
55 changes: 21 additions & 34 deletions MRICenterline/app/database/openable_sessions.py
Original file line number Diff line number Diff line change
@@ -1,46 +1,33 @@
import sqlite3

from MRICenterline.app.database import name_id
from MRICenterline import CFG


def get_all_sessions():
con = sqlite3.connect(CFG.get_db())
sessions = con.cursor().execute("""
select session_id, lengths_id, cl_id, timestamp, case_name, name
from sessions
inner join case_list
on case_list.case_id = sessions.case_id
inner join sequences
on sequences.seq_id = sessions.seq_id
""").fetchall()

sessions_list, case_names, timestamps, seq_names, length, centerline = [], [], [], [], [], []
for session_id, lengths_id, cl_id, timestamp, case_name, name in sessions:
case_names.append(case_name)
timestamps.append(timestamp)
seq_names.append(name)
sessions_list.append(session_id)

if lengths_id:
length.append(con.cursor().execute(
f"select count(*) from 'length_coordinates' where lengths_id_id = {lengths_id}").fetchone()[0])
else:
length.append(0)

if cl_id:
centerline.append(con.cursor().execute(
f"SELECT count(*) FROM 'centerline_coordinates' where cl_id = {cl_id}").fetchone()[0])
else:
centerline.append(0)
sessions = con.cursor().execute("select * from 'sessions'").fetchall()
session_table_headers = [i[1] for i in con.cursor().execute("select * from pragma_table_info('sessions');").fetchall()]

dat = {h: list() for h in session_table_headers}
for s in sessions:
conv = list(s)
conv[5] = name_id.get_sequence_name(s[5], s[6])
conv[6] = name_id.get_case_name(s[6])
for (_, li), i in zip(dat.items(), conv):
li.append(i)

con.close()

return {"case name": case_names,
"timestamps": timestamps,
"sequence name": seq_names,
'length points': length,
'centerline points': centerline,
'session_id': sessions_list}, len(sessions)
dat.pop('lengths_id')
dat.pop('cl_id')
return dat, len(sessions)


def get_latest_sessions():
pass
# select * from 'sessions' group by case_id order by timestamp desc
pass


if __name__ == "__main__":
print(get_all_sessions())
30 changes: 18 additions & 12 deletions MRICenterline/app/database/save_points.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,16 @@ def save_points(case_name: str,
from 'length_coordinates'
)""").fetchone()[0] + 1
for pt in length_points:
length_insert_query = """insert into 'length_coordinates'
(lengths_id, x, y, z)
values
(?, ?, ?, ?)
"""
with con:
con.execute("""insert into 'length_coordinates'
(lengths_id, x, y, z)
values
(?, ?, ?, ?)
""",
(lengths_id, *pt.physical_coords))
if CFG.get_testing_status("use-slice-location"):
con.execute(length_insert_query, (lengths_id, *pt.image_coordinates))
else:
con.execute(length_insert_query, (lengths_id, *pt.physical_coords))
else:
lengths_id = None

Expand All @@ -52,13 +55,16 @@ def save_points(case_name: str,
from 'centerline_coordinates'
)""").fetchone()[0] + 1
for pt in mpr_points:
cl_insert_query = """insert into centerline_coordinates
(cl_id, x, y, z)
values
(?, ?, ?, ?)
"""
with con:
con.execute("""insert into centerline_coordinates
(cl_id, x, y, z)
values
(?, ?, ?, ?)
""",
(cl_id, *pt.physical_coords))
if CFG.get_testing_status("use-slice-location"):
con.execute(cl_insert_query, (cl_id, *pt.image_coordinates))
else:
con.execute(cl_insert_query, (cl_id, *pt.physical_coords))
else:
cl_id = None

Expand Down
12 changes: 7 additions & 5 deletions MRICenterline/app/file_reader/dicom/DICOMReader.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def get_file_list(self, seq):

if type(seq) is str:
query = f"""
select distinct filename from slice_locations
select distinct filename, slice_location from slice_locations
inner join sequence_files
on sequence_files.file_id = slice_locations.file_id
inner join sequences
Expand All @@ -60,9 +60,9 @@ def get_file_list(self, seq):
and sequence_files.case_id = {self.case_id}
order by slice_location asc;
"""
file_list = [item[0] for item in con.cursor().execute(query).fetchall()]
file_and_slice_list = [(item[0], item[1]) for item in con.cursor().execute(query).fetchall()]
con.close()
return [os.path.join(self.folder, i) for i in file_list]
return [(os.path.join(self.folder, f), loc) for f, loc in file_and_slice_list]
elif type(seq) is int:
return self.get_file_list(self.sequence_list[seq])

Expand Down Expand Up @@ -114,14 +114,16 @@ def generate(file_list):
import pydicom
import numpy as np

file_list.sort(key=lambda x: x[1])

def get_pixel_array(f):
with open(f, 'rb') as f:
ds = pydicom.dcmread(f)
return ds.pixel_array

np_out = np.array([get_pixel_array(f) for f in file_list])
np_out = np.array([get_pixel_array(f) for f, _ in file_list])

return np_out, file_list
return np_out, [f for f, _ in file_list]
else:
reader = sitk.ImageSeriesReader()

Expand Down
2 changes: 2 additions & 0 deletions MRICenterline/app/gui_data_handling/sequence_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,5 +167,7 @@ def load_points(self, length_id, mpr_id):
for pt in self.mpr_point_array.get_actor_list():
self.current_sequence_viewer.add_actor(pt)

logging.info(f"Reading from MPR [{mpr_id}]")

print(len(self.length_point_array))
print(len(self.mpr_point_array))
7 changes: 5 additions & 2 deletions MRICenterline/app/gui_data_handling/sequence_viewer.py
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ def adjust_slice_idx(self, delta: int):

slice_idx = 1 + np.int(np.round(((center[2] - self.image.origin[2]) / self.image.spacing[2])))

if 1 <= slice_idx <= self.image.size[2]:
if 1 <= slice_idx < self.image.size[2]:
matrix = self.reslice.GetResliceAxes()
matrix.SetElement(0, 3, center[0])
matrix.SetElement(1, 3, center[1])
Expand All @@ -245,7 +245,10 @@ def adjust_slice_idx(self, delta: int):
self.image.sliceIdx = slice_idx
self.display_points_in_slice(slice_idx)

self.update_status_text("Slice Index", 1 + self.image.size[2] - self.slice_idx)
if CFG.get_testing_status("use-slice-location"):
self.update_status_text("Slice Index", self.slice_idx)
else:
self.update_status_text("Slice Index", 1 + self.image.size[2] - self.slice_idx)
self.render_panel()

######################################################################
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,17 +36,27 @@ def __init__(self, np_array, z_coords, file_list, parent=None):
self.nparray = numpy_support.vtk_to_numpy(self.vtk_data.GetPointData().GetArray(0))
self.nparray = self.nparray.reshape(self.dimensions, order='F')

min_z = round(center_z - (self.origin[2] + self.spacing[2] * (self.dimensions[2])), 1)
max_z = math.ceil((self.dimensions[2] * self.spacing[2]) + min_z)

self.z_coords = sorted(list(set(z_coords)))

x0, y0, z0 = self.origin
x_spacing, y_spacing, z_spacing = self.spacing
x_min, x_max, y_min, y_max, z_min, z_max = self.extent

center = [x0 + x_spacing * 0.5 * (x_min + x_max),
y0 + y_spacing * 0.5 * (y_min + y_max),
z0 + z_spacing * 0.5 * (z_min + z_max)]

self.transformation = vtk.vtkMatrix4x4()
self.transformation.DeepCopy((1, 0, 0, center[0],
0, -1, 0, center[1],
0, 0, 1, center[2],
0, 0, 0, 1))

@staticmethod
def get_vtk_data_old(np_arr, origin, spacing, ncomp, direction, size):
""" adapted from https://github.com/dave3d/dicom2stl/blob/main/utils/sitk2vtk.py """

np_arr = np.flipud(np_arr) # either this, or reshape with order F? TODO: check this
np_arr = np.fliplr(np_arr)
vtk_image = vtk.vtkImageData()

size = list(size)
Expand Down Expand Up @@ -86,11 +96,4 @@ def get_vtk_data_old(np_arr, origin, spacing, ncomp, direction, size):

vtk_image.Modified()

print("Volume object inside sitk2vtk")
# print(vtk_image)
print(size)
print(origin)
print(spacing)
# print(vtk_image.GetScalarComponentAsFloat(0, 0, 0, 0))

return vtk_image
29 changes: 9 additions & 20 deletions MRICenterline/app/points/point.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,11 @@ def point_from_physical(cls, physical_coords, image_properties, color=(1, 1, 1),

return cls(image_coordinates, slice_idx, image_properties, color, size)

@classmethod
def point_from_vtk_coords(cls, image_coordinates, image_properties, color=(1, 1, 1), size=3):
slice_idx = int(np.argmin(np.abs(np.array(image_properties.z_coords) - image_coordinates[2])))
return cls(image_coordinates, slice_idx, image_properties, color, size)

def generate_actor(self):
source = vtkSphereSource()
source.SetCenter(self.image_coordinates[0], self.image_coordinates[1], 0)
Expand Down Expand Up @@ -96,26 +101,10 @@ def __repr__(self):
def calculate_itk(self):
viewer_origin = self.image_properties.size / 2.0

itk_coords = np.zeros(3)

# round(coords[0]/spacing[0] + viewerOrigin[0])
itk_coords[0] = (
self.image_coordinates[0]/self.image_properties.spacing[0]
+ viewer_origin[0]
)

# round(shape[1] - (coords[1] / spacing[1] + viewerOrigin[1]))
itk_coords[1] = (
self.image_properties.size[1] -
(
self.image_coordinates[1] / self.image_properties.spacing[1]
+ viewer_origin[1]
)
)

itk_coords[2] = self.slice_idx + 1

itk_coords = np.int32(itk_coords)
itk_coords = np.zeros(3, dtype=np.int32)
itk_coords[0] = round(self.image_coordinates[0] / self.image_properties.spacing[0] + viewer_origin[0])
itk_coords[1] = round(self.image_properties.dimensions[1] - (self.image_coordinates[1] / self.image_properties.spacing[1] + viewer_origin[1]))
itk_coords[2] = np.argmin(np.abs(np.array(self.image_properties.z_coords) - self.image_coordinates[2]))

physical_coords = self.image_properties.sitk_image.TransformIndexToPhysicalPoint([int(itk_coords[0]), int(itk_coords[1]), int(itk_coords[2])])
# TODO: check TransformContinuousIndexToPhysicalPoint, it produces different results
Expand Down
1 change: 1 addition & 0 deletions MRICenterline/app/scanner/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .organize_data import run_organize_data
from .time_report import run_time_report
from .run_metadata_sequence_scan import run_metadata_sequence_scan
from .load_v3_points import load_v3_points
8 changes: 8 additions & 0 deletions MRICenterline/app/scanner/load_v3_points.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
from pathlib import Path

import logging
logging.getLogger(__name__)


def load_v3_points(folder: str or Path):
pass
10 changes: 1 addition & 9 deletions MRICenterline/cli/__init__.py
Original file line number Diff line number Diff line change
@@ -1,9 +1 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
documentation
"""

if __name__ == '__main__':
pass
from .arg_setup import arg_setup
46 changes: 38 additions & 8 deletions MRICenterline/cli/arg_setup.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,40 @@
from MRICenterline.CommandLineInterface import run_folder_scan
import sys
import argparse

opts = [opt for opt in sys.argv[1:] if opt.startswith("-")]
args = [arg for arg in sys.argv[1:] if not arg.startswith("-")]
from MRICenterline.app import scanner

if "-f" in opts:
run_folder_scan(args)
else:
raise SystemError("Please see usage instructions.")
import logging
logging.getLogger(__name__)


def arg_setup():
parser = argparse.ArgumentParser(description='ImageUntangler CLI version')

parser.add_argument('-f', '--folder', action='store', type=str,
help="Folder to scan", required=True)

arguments = [
("-s", "--scan", "Generate sequence/metadata report"),
("-o", "--org", "Organize folder data"),
("-t", "--time", "Generate timing report"),
("-v3", "--ver3", "Load points from v3")
]

for sh, lo, he in arguments:
parser.add_argument(sh, lo, action='store_true', help=he)

args = parser.parse_args()

logging.info(f"Starting scan: {args.folder}")

# TODO: create a temporary CFG file for the scanner to use

if args.scan:
logging.info("Generate sequence/metadata report")
if args.org:
logging.info("Organize folder data")
if args.time:
logging.info("Generate timing report")
if args.ver3:
logging.info("Load points from v3")
scanner.run_metadata_sequence_scan(args.folder)
scanner.load_v3_points(args.folder)
4 changes: 4 additions & 0 deletions MRICenterline/gui/display/configure.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@

from MRICenterline import CONST, CFG

import logging
logging.getLogger(__name__)


def configure_main_widget(path, parent_widget, selected_sequence=None):
window = parent_widget.window()
Expand Down Expand Up @@ -56,6 +59,7 @@ def configure_main_widget_from_session(parent_widget, session_id):
centerline_model.connect_widget(centerline_widget)

case_model.load_points(lengths_id, cl_id)
logging.info(f"Loaded points from session with ID [{session_id}]")

splitter = QSplitter(window)
splitter.setOrientation(Qt.Vertical)
Expand Down
Loading

0 comments on commit d63d5b3

Please sign in to comment.