<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">import matplotlib
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import os
import tkMessageBox
import Tkinter as tk
import sys
import SimpleITK as sitk
import dicom
import XMLparser
import csv
import skimage.measure as sk
import scipy

class RectTracker:
    def __init__(self, rect):
        self.rect = rect
        self.curA = plt.gca()
        self.start = None
        self.rectangles = ['none', 'none', 'none', 'none']

    def connect(self, save):
        'connect to all the events we need'
        self.start = None
        self.save = save
        self.cidpress = self.rect.figure.canvas.mpl_connect(
            'button_press_event', self.on_press)
        self.cidrelease = self.rect.figure.canvas.mpl_connect(
            'button_release_event', self.on_release)
        self.cidmotion = self.rect.figure.canvas.mpl_connect(
            'motion_notify_event', self.on_motion)

    def on_press(self, event):
        'on button press we will see if the mouse is over us and store some data'
        if self.rect.toolbar._active is None:
            try:
                self.rectangles[self.save].remove()
            except:
                pass

            if event.inaxes != self.curA.axes: return

            contains, attrd = self.curA.contains(event)
            if not contains: return

            self.start = event.xdata, event.ydata

    def on_motion(self, event):
        'on motion we will move the rect if the mouse is over us'
        if self.start is None: return
        if event.inaxes != self.curA.axes: return
        xpress, ypress = self.start
        dx = event.xdata - xpress
        dy = (event.ydata - ypress)

        self.end = xpress+dx, ypress+dy

        color = ['r', 'y', 'm', 'c']
        self.obj = matplotlib.patches.Rectangle(self.start, dx, dy, fill="", lw = 2, ec = color[self.save])
        self.curA.add_patch(self.obj)

        # draw everything but the selected patch and store the pixel buffer
        canvas = self.obj.figure.canvas
        axes = self.obj.axes
        self.obj.set_animated(True)
        canvas.draw()
        self.background = canvas.copy_from_bbox(self.obj.axes.bbox)

        # now redraw just the patch
        axes.draw_artist(self.obj)

        # and blit just the redrawn area
        canvas.blit(axes.bbox)



    def on_release(self, event):
        if self.rect.toolbar._active is None:
            'on release we reset the press data'
            if self.start is None: return
            self.rectangles[self.save] = self.obj
            self.obj.set_animated(False)
            # self.obj.figure.canvas.draw()
            self.start = None


    def disconnect(self):
        'disconnect all the stored connection ids'
        try:
            self.rect.figure.canvas.mpl_disconnect(self.cidpress)
            self.rect.figure.canvas.mpl_disconnect(self.cidrelease)
            self.rect.figure.canvas.mpl_disconnect(self.cidmotion)
        except:
            pass


class App(tk.Tk):
    def __init__(self,parent):
        tk.Tk.__init__(self,parent)
        self.parent = parent
        self.protocol("WM_DELETE_WINDOW", self.dest)
        self.getAccepted()
        self.main()

    def main(self):
        self.columnconfigure(0, weight=1)
        self.rowconfigure(0, weight=1)
        self.rowconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
        self.rowconfigure(3, weight=1)
        self.minsize(600, 550)

        self.h = self.winfo_screenheight()

        self.fig = plt.figure()
        self.fig = plt.figure(figsize=(self.h/70, self.h/90))

        self.frame = tk.Frame(self)
        self.frame.grid(row=0, column=0, rowspan=5)

        self.title("Select tissue type on right and then draw rectangle enclosing the respective tissue")

        self.canvas = FigureCanvasTkAgg(self.fig, master=self.frame)

        self.canvas.get_tk_widget().grid(row=0, column=0)

        self.canvas._tkcanvas.grid(row=0, column=0)

        self.toolbar = NavigationToolbar2TkAgg(self.canvas, self)
        self.toolbar.update()
        self.toolbar.grid(row=4, column=0, sticky='ewns')

        self.btn1 = tk.Button(self, text="Skin", command=lambda: self.skin())
        self.btn1.grid(row=0, column=1, sticky='ewns')
        self.btn2 = tk.Button(self, text="Fat", command=lambda: self.fat())
        self.btn2.grid(row=1, column=1, sticky='ewns')
        self.btn3 = tk.Button(self, text="Muscle", command=lambda: self.muscle())
        self.btn3.grid(row=2, column=1,sticky='ewns')
        self.btn4 = tk.Button(self, text="Bone", command=lambda: self.bone())
        self.btn4.grid(row=3, column=1, sticky='ewns')
        tk.Button(self, text="Next", command=lambda: self.next_img()).grid(row=5, column=0, sticky='ewns')
        tk.Button(self, text="Done", command=lambda: self.done()).grid(row=6, column=0, sticky='ewns')

        self.get_image(self.DCM_accepted[self.mm])

        self.track = RectTracker(self.canvas)

    def skin(self):
        self.btn1.configure(bg='red')
        self.track.connect(0)

    def fat(self):
        self.btn2.configure(bg='yellow')
        self.track.connect(1)

    def muscle(self):
        self.btn3.configure(bg='magenta')
        self.track.connect(2)

    def bone(self):
        self.btn4.configure(bg='cyan')
        self.track.connect(3)

    def next_img(self):
        self.mm += 1
        self.get_image(self.DCM_accepted[self.mm])
        self.btn1.configure(bg='light grey')
        self.btn2.configure(bg='light grey')
        self.btn3.configure(bg='light grey')
        self.btn4.configure(bg='light grey')
        self.track.disconnect()
        self.track = RectTracker(self.canvas)


    def done(self):
        DCM = self.DCM_accepted[self.mm]
        split_name = os.path.split(DCM)
        name = split_name[1][0:3]
        img = self.nda
        labels = np.zeros(img.shape, dtype=np.uint)
        # np.int64(labels)


        lst = []
        for R in self.track.rectangles:
            if R != 'none':
                xy = R.get_xy()
                xf = xy[0] + R.get_width()
                yf = xy[1] + R.get_height()
                lst.append([int(xy[1]), int(yf), int(xy[0]), int(xf)])
            else:
                lst.append([])

        matrix = []
        try:
            # matrix.append([name, 'skin', img[lst[0][0]:lst[0][1], lst[0][2]:lst[0][3], 0]])
            # matrix.append([name, 'fat', img[lst[1][0]:lst[1][1], lst[1][2]:lst[1][3], 0]])
            # matrix.append([name, 'muscle', img[lst[2][0]:lst[2][1], lst[2][2]:lst[2][3], 0]])
            # matrix.append([name, 'bone', img[lst[3][0]:lst[3][1], lst[3][2]:lst[3][3], 0]])
            labels[lst[0][0]:lst[0][1], lst[0][2]:lst[0][3], 0] = 1
            labels[lst[1][0]:lst[1][1], lst[1][2]:lst[1][3], 0] = 2
            labels[lst[2][0]:lst[2][1], lst[2][2]:lst[2][3], 0] = 3
            labels[lst[3][0]:lst[3][1], lst[3][2]:lst[3][3], 0] = 4


        except:
            tkMessageBox.showerror("Error",
                                   "One or more of the tissues has not been selected, please select a box for each"
                                   " tissue type")

        self.saveimage(img, name+'regions.jpg')
        self.saveimage(labels, name+'regions_labeled.jpg')

    def saveimage(self, IMG, fname):
        scipy.misc.imsave(fname, IMG)

    # def calculateData(self, matrix):
    #
    #     with open(r'data.csv', 'a') as f:
    #         writer = csv.writer(f, delimiter=',')
    #         for tissue in matrix:
    #             x_max = np.amax(tissue[2], axis=1)
    #             x_min = np.amin(tissue[2], axis=1)
    #             y_max = np.amax(tissue[2], axis=0)
    #             y_min = np.amin(tissue[2], axis=0)
    #             m = sk.moments(tissue[2])
    #             m_c = sk.moments_central(tissue[2], m[0, 1] / m[0, 0], m[1, 0] / m[0, 0])
    #             print(sk.moments_hu(m_c)[0])
    #             # writer.writerow([tissue[0], tissue[1], tissue[2].shape[1], tissue[2].shape[0], self.convFact,np.mean(tissue[2]), np.std(tissue[2]), np.min(tissue[2]), np.max(tissue[2])], np.mean(x_max-x_min), np.mean(y_max-y_min))


    def getAccepted(self):

        self.mm = 0

        self.getFiles()

        self.DCM_accepted = []
        self.TDMS_accepted = []
        self.acceptedList = []

        for ii in self.masterList:
            if ii[1] == 1:
                self.acceptedList.append(ii[0])

        for FF in self.lstFilesDCM:
            name = os.path.split(FF)
            if name[1][0:3] in self.acceptedList:
                self.DCM_accepted.append(FF)

        for FF in self.lstFilesTDMS:
            name = os.path.split(FF)
            if name[1][0:3] in self.acceptedList:
                self.TDMS_accepted.append(FF)

    def dest(self):
        self.destroy()
        sys.exit()

    def getFiles(self):
        """Get accepted trials for the selected subject, this includes the Ultrasound dicom images, Data tdms files,
        and the TimeSynchronization txt file. The program can either open a File Dialog box to search for the directory,
        or the user can hard code the directory"""
        # Hard code Subject Directory
        self.directoryname = '/home/morrile2/Documents/MULTIS_test/MULTIS001-1'

        self.lstFilesDCM = []  # create an empty list for DICOM files
        self.lstFilesTDMS = []  # create an empty list for TDMS files

        self.masterList, self.num_accept = XMLparser.getAcceptance(self.directoryname)

        # Find DICOM and TDMS files
        for self.dirName, self.subdirList, self.fileList in os.walk(self.directoryname):
            for filename in self.fileList:
                if ".ima" in filename.lower():  # check whether the file's DICOM
                    self.lstFilesDCM.append(os.path.join(self.dirName, filename))
                elif ".tdms" in filename.lower():  # check whether the file's TDMS
                    self.lstFilesTDMS.append(os.path.join(self.dirName, filename))

        # Sort variables by trial number
        self.lstFilesTDMS.sort()
        self.lstFilesDCM.sort()

    def get_image(self, DCM_name):
        self.fig.clear()

        img_idx = 0
        reader = sitk.ImageFileReader()
        reader.SetFileName(DCM_name)
        img_all = reader.Execute()

        self.RefDs = dicom.read_file(DCM_name)
        seq = self.RefDs.SequenceofUltrasoundRegions
        self.convFact = seq[0].PhysicalDeltaY * 10

        # Read in the appropriate dicom frame and set up plot title
        img = img_all[:, :, img_idx]
        self.nda = sitk.GetArrayFromImage(img)

        plt.imshow(self.nda[:, :, 0], cmap="gray")
        split_name = os.path.split(self.TDMS_accepted[self.mm])
        plt.title('\n' + split_name[1][0:25] + '  :  Frame = ' + str(img_idx))

        self.canvas.draw()


if __name__ == "__main__":
    app = App(None)
    app.mainloop()</pre></body></html>