Ejemplo n.º 1
0
    def _run_interface(self, runtime):
        if not isdefined(self.inputs.output_file):
            self.inputs.output_file = self._gen_output(self.inputs.in_file,
                                                       self._suffix)
        print self.inputs.in_file
        print self.inputs.reference
        header = self.inputs.header
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.output_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:
            try:
                time_frames = [
                    float(s) for s, e in header['Time']["FrameTimes"]["Values"]
                ]
            except ValueError:
                time_frames = [1.]

            vol = simps(pet.data, time_frames, axis=4)

        idx = reference.data > 0
        ref = np.mean(vol[idx])
        print "SUVR Reference = ", ref
        vol = vol / ref
        out.data = vol
        out.writeFile()
        out.closeVolume()

        return runtime
Ejemplo n.º 2
0
    def _run_interface(self, runtime):
        header = json.load(open(self.inputs.header, "r"))
        if not isdefined(self.inputs.out_file):
            self.inputs.out_file = self._gen_output(self.inputs.in_file,
                                                    self._suffix)

        try:
            dose = float(header["RadioChem"]["InjectedRadioactivity"])
        except ValueError:
            print(
                "Error: Could not find injected dose in subject's header. Make sure subject has a .json header in BIDS format with [RadioChem][InjectedRadioactivity]"
            )
            exit(1)

        try:
            weight = float(header["Info"]["BodyWeight"])
        except ValueError:
            print(
                "Error: Could not find subject's body weight in header. Make sure subject has a .json header in BIDS format with [Info][BodyWeight]"
            )
            exit(1)
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.out_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:
            dims = pet.getDimensionNames()
            i = dims.index('time')

            if not isdefined(self.inputs.start_time):
                start_time = 0
            else:
                start_time = self.inputs.start_time

            if not isdefined(self.inputs.end_time):
                end_time = header['Time']['FrameTimes']['Values'][-1][1]
            else:
                end_time = self.inputs.end_time

            #time_frames = time_indices = []
            #for i in range(vol.shape[i]) :
            #    s=header['Time']["FrameTimes"]["Values"][i][0]
            #    e=header['Time']["FrameTimes"]["Values"][i][1]
            #    print(i)
            #    if s >= start_time and e <= end_time :
            #        time_indices.append(i)
            #        time_frames.append(float(e) - float(s)  )
            #print(time_indices)
            #print(time_frames)
            time_frames = [
                float(s) for s, e in header['Time']["FrameTimes"]["Values"]
            ]
            vol = simps(pet.data, time_frames, axis=i)
        vol = vol / (dose / weight)
        out.data = vol
        out.writeFile()
        out.closeVolume()
        return runtime
Ejemplo n.º 3
0
def mnc_labeling(g, CT_file, output_file, multiplier=1.0):
    #labeled_ct = f.volumeFromFile(CT_file)
    labeled_ct = f.volumeLikeFile(CT_file, output_file)
    #labeled_ct.openFile()
    size = labeled_ct.getSizes()
    print "CT size is ", size
    print "first and last voxel intensities are:", labeled_ct.data[0, 0, 0]
    print labeled_ct.data[size[0] - 1, size[1] - 1, size[2] - 1]
    spacing = labeled_ct.getSeparations()
    start = labeled_ct.getStarts()
    #set the volume to 0
    for i in range(size[0]):
        for j in range(size[1]):
            for k in range(size[2]):
                labeled_ct.data[i, j, k] = 0
    #set the labels
    for e in g.edge_list():
        l = g.edge_property(e, 'label')
        vlist = [e[0]] + [e[1]] + g.edge_property(e, 'intermediaries')
        for v in vlist:
            w = g.vertices[v].centre
            r = multiplier * g.vertices[v].radius
            wtovfloat = labeled_ct.convertWorldToVoxel(w)
            wtov = np.array(
                [int(wtovfloat[0]),
                 int(wtovfloat[1]),
                 int(wtovfloat[2])])
            if wtov[0] < size[0] and wtov[1] < size[1] and wtov[2] < size[
                    2] and wtov[0] > -1 and wtov[1] > -1 and wtov[2] > -1:
                labeled_ct.data[int(wtov[0]), int(wtov[1]), int(wtov[2])] = l
            for i in range(max(0, int(wtov[0] - (r / spacing[0]))),
                           min(int(wtov[0] + (r / spacing[0])), size[0])):
                for j in range(max(0, int(wtov[1] - (r / spacing[1]))),
                               min(int(wtov[1] + (r / spacing[1])), size[1])):
                    for k in range(
                            max(0, int(wtov[2] - (r / spacing[2]))),
                            min(int(wtov[2] + (r / spacing[2])), size[2])):
                        currw = labeled_ct.convertWorldToVoxel(
                            np.array([i, j, k]))
                        if calc_dist(w[0] - currw[0], w[1] - currw[1],
                                     w[2] - currw[2]) < r:
                            labeled_ct.data[int(i), int(j), int(k)] = l

    labeled_ct.writeFile()
    labeled_ct.closeVolume()
    return 0
Ejemplo n.º 4
0
    def _run_interface(self, runtime):
        if not isdefined(self.inputs.out_file):
            self.inputs.out_file = self._gen_output(self.inputs.in_file,
                                                    self._suffix)
        header = json.load(open(self.inputs.header, "r"))
        pet = volumeFromFile(self.inputs.in_file)
        reference = volumeFromFile(self.inputs.reference)
        out = volumeLikeFile(self.inputs.reference, self.inputs.out_file)
        ndim = len(pet.data.shape)

        vol = pet.data
        if ndim > 3:

            dims = pet.getDimensionNames()
            i = dims.index('time')

            if not isdefined(self.inputs.start_time):
                start_time = 0
            else:
                start_time = self.inputs.start_time

            if not isdefined(self.inputs.end_time):
                end_time = header['Time']['FrameTimes']['Values'][-1][1]
            else:
                end_time = self.inputs.end_time

            try:
                #time_frames = [ float(s) for s,e in  header['Time']["FrameTimes"]["Values"] ]
                time_frames = [
                    float(s) for s, e in header['Time']["FrameTimes"]["Values"]
                    if s >= start_time and e <= end_time
                ]
            except ValueError:
                time_frames = [1.]
            vol = simps(pet.data, time_frames, axis=i)

        idx = reference.data > 0
        ref = np.mean(vol[idx])
        print "SUVR Reference = ", ref
        vol = vol / ref
        out.data = vol
        out.writeFile()
        out.closeVolume()

        return runtime
Ejemplo n.º 5
0
def do_component(component_nr):
    input_volume = volumeFromFile(
        '/scratch/intersection_output_disjoint/input_%d.mnc' % component_nr)

    output_volume = volumeLikeFile(
        '/scratch/intersection_output_disjoint/input_%d.mnc' % component_nr,
        '/scratch/final_smoothed_disjoint_components/component_%d.mnc' %
        component_nr,
        dtype='ubyte')

    for j in range(input_volume.data.shape[1]):
        print component_nr, j

        output_volume.data[:, j, :] = blerp(input_volume.data[:, j, :])

    output_volume.writeFile()
    output_volume.closeVolume()

    input_volume.closeVolume()
    """
Ejemplo n.º 6
0
def predict(model_name,input_path,input_filenames,output_path,output_filename,stride=(2,1,1)):

    #model = load_model_own(model_name,model_version=model_version)
    model = load_model(model_name)
    (_,x,y,z,d) = model.input.shape.as_list()
    patchsize = (x,y,z)

    l = []
    for n in range(0,d):
        mncfile = os.path.join(input_path,input_filenames[n])
        img = load_minc_as_np(mncfile)
        patches = get_patches(img,patchsize,stride)
        l.append(patches)
    patches = np.concatenate(l,axis=4)

    out_vol = pyminc.volumeLikeFile(os.path.join(input_path,input_filenames[0]),os.path.join(output_path,output_filename))
    containersize= out_vol.data.shape
    predicted_vol =  model_predict_from_patches(model,patches,containersize,stride=stride)
    out_vol.data = predicted_vol
    out_vol.writeFile()
    out_vol.closeVolume()
    print('Done predicting: ' + os.path.join(output_path,output_filename))
Ejemplo n.º 7
0
try:
	RTSS = dicom.read_file(args.RTX) 
	print RTSS.StructureSetROISequence[0].ROIName
	ROIs = RTSS.ROIContourSequence

	if args.verbose:
		print "Found",len(ROIs),"ROIs"

	volume = pyminc.volumeFromFile(args.MINC)

	for ROI_id,ROI in enumerate(ROIs):

		# Create one MNC output file per ROI
		RTMINC_outname = args.RTMINC if len(ROIs) == 1 else args.RTMINC[:-4] + "_" + str(ROI_id) + ".mnc"
		RTMINC = pyminc.volumeLikeFile(args.MINC,RTMINC_outname)
		contour_sequences = ROI.ContourSequence

		if args.verbose:
			print " --> Found",len(contour_sequences),"contour sequences for ROI:",RTSS.StructureSetROISequence[ROI_id].ROIName

		for contour in contour_sequences:
			assert contour.ContourGeometricType == "CLOSED_PLANAR"

			current_slice_i_print = 0
			
			if args.verbose:
				print "\t",contour.ContourNumber,"contains",contour.NumberOfContourPoints

			world_coordinate_points = np.array(contour.ContourData)
			world_coordinate_points = world_coordinate_points.reshape((contour.NumberOfContourPoints,3))
Ejemplo n.º 8
0
def pyrtx2mnc():
    #Read dicom rt structure file with pydicom
    RTSS = dicom.read_file(args.RTX)
    if args.verbose:
        print "Regions found: {}".format(
            RTSS.StructureSetROISequence[0].ROIName)
    #Fetch the minc volume from the input
    volume = pyminc.volumeFromFile(args.MINC)
    #For every ROI encountered create a seperate mapping and file.
    for ROI_id, ROI in enumerate(RTSS.ROIContourSequence):

        # Create one MNC output file per ROI
        RTMINC_outname = args.RTMINC if len(
            RTSS.ROIContourSequence
        ) == 1 else args.RTMINC[:-4] + "_" + str(ROI_id) + ".mnc"
        #Create volume like the minc file and name it RTMINC_outname
        RTMINC = pyminc.volumeLikeFile(args.MINC, RTMINC_outname)
        contour_sequences = ROI.ContourSequence
        if args.verbose:
            print " --> Found", len(
                contour_sequences
            ), "contour sequences for ROI:", RTSS.StructureSetROISequence[
                ROI_id].ROIName
        #For each contoursequence convert world coordinates, draw the contour, check if the drawn points are inside a voxel center grid
        for contour in contour_sequences:
            #Raise error if we do not have a CLOSED_PLANAR type.
            assert contour.ContourGeometricType == "CLOSED_PLANAR"

            if args.verbose:
                print "\t", contour.ContourNumber, "contains", contour.NumberOfContourPoints

            #Convert contourdata to numpy array and reshape as xyz coloumns
            world_coordinate_points = np.array(contour.ContourData).reshape(
                (contour.NumberOfContourPoints, 3))
            #Create empty 2d slice(array) with the original slice dimensions
            current_slice = np.zeros(
                (volume.getSizes()[1], volume.getSizes()[2]))
            current_slice_inner = np.zeros(
                (volume.getSizes()[1], volume.getSizes()[2]), dtype=np.float)
            #Create empty 2d array of size of the x,y coordinates
            voxel_coordinates_inplane = np.zeros(
                (len(world_coordinate_points), 2))
            current_slice_i = 0
            #Convert world to voxel and set current_slice to the z space or slice number add x,y coordinates to the voxel_coordinates_inplane
            for wi, world in enumerate(world_coordinate_points):
                voxel = volume.convertWorldToVoxel(
                    [-world[0], -world[1], world[2]])
                current_slice_i = voxel[0]
                voxel_coordinates_inplane[wi, :] = [voxel[2], voxel[1]]
            #Round x,y coordinates and convert to array again
            converted_voxel_coordinates_inplane = np.array(
                np.round(voxel_coordinates_inplane), np.int32)
            #Fill the contour place result in image current_slice_inner array
            cv2.fillPoly(current_slice_inner,
                         pts=[converted_voxel_coordinates_inplane],
                         color=1)
            #only return the two tuples that are not zero convert to array and transpose them
            points = np.array(np.nonzero(current_slice_inner)).T
            #Path converts the inplane voxels to a path class with callable values such as contains_points and more(https://matplotlib.org/api/path_api.html)
            p = Path(voxel_coordinates_inplane)
            #Create np.array of True or false values if the points are in the path
            grid = p.contains_points(points[:, [1, 0]])

            for pi, point in enumerate(points):
                if not grid[pi]:
                    # REMOVE EDGE POINT BECAUSE CENTER IS NOT INCLUDED
                    current_slice_inner[point[0], point[1]] = 0

            #Only change the data structure inside the minc volume created earlier
            RTMINC.data[np.int(current_slice_i)] += current_slice_inner

        # Remove even areas - implies a hole.
        RTMINC.data[RTMINC.data % 2 == 0] = 0
        #Write and close file
        RTMINC.writeFile()
        RTMINC.closeVolume()
        #Copy the name of the RTstruct (defined in Mirada) to the name of the MNC file
        if args.verbose:
            print 'minc_modify_header -sinsert dicom_0x0008:el_0x103e="' + RTSS.StructureSetROISequence[
                ROI_id].ROIName + '" ' + RTMINC_outname
        os.system('minc_modify_header -sinsert dicom_0x0008:el_0x103e="' +
                  RTSS.StructureSetROISequence[ROI_id].ROIName + '" ' +
                  RTMINC_outname)

    volume.closeVolume()