Beispiel #1
0
    def __init__(self, directory):
        self.basePath = directory
        self.layers = []
        self.data = []
        self.imageReader = vtkPNGReader()

        # Load JSON metadata
        with open(os.path.join(directory, "config.json"), "r") as f:
            self.config = json.load(f)
            self.nbLayers = len(self.config['scene'])
            while len(self.layers) < self.nbLayers:
                self.layers.append({})

        with open(os.path.join(directory, "index.json"), "r") as f:
            self.info = json.load(f)

        with open(os.path.join(directory, "offset.json"), "r") as f:
            offsets = json.load(f)
            for key, value in iteritems(offsets):
                meta = key.split('|')
                if len(meta) == 2:
                    self.layers[int(meta[0])][meta[1]] = value
                elif meta[1] in self.layers[int(meta[0])]:
                    self.layers[int(meta[0])][meta[1]][int(meta[2])] = value
                else:
                    self.layers[int(meta[0])][meta[1]] = [value, value, value]

        self.composite = CompositeJSON(len(self.layers))
Beispiel #2
0
    def __init__(self, directory):
        self.basePath = directory
        self.layers = []
        self.data = []
        self.imageReader = vtkPNGReader()

        # Load JSON metadata
        with open(os.path.join(directory, "config.json"), "r") as f:
            self.config = json.load(f)
            self.nbLayers = len(self.config["scene"])
            while len(self.layers) < self.nbLayers:
                self.layers.append({})

        with open(os.path.join(directory, "index.json"), "r") as f:
            self.info = json.load(f)

        with open(os.path.join(directory, "offset.json"), "r") as f:
            offsets = json.load(f)
            for key, value in iteritems(offsets):
                meta = key.split("|")
                if len(meta) == 2:
                    self.layers[int(meta[0])][meta[1]] = value
                elif meta[1] in self.layers[int(meta[0])]:
                    self.layers[int(meta[0])][meta[1]][int(meta[2])] = value
                else:
                    self.layers[int(meta[0])][meta[1]] = [value, value, value]

        self.composite = CompositeJSON(len(self.layers))
    def __init__(self, isWriter=True, removePNG=True):
        self.view = simple.CreateView('RenderView')
        self.view.Background = [0.0, 0.0, 0.0]
        self.view.CenterAxesVisibility = 0
        self.view.OrientationAxesVisibility = 0

        self.reader = vtkPNGReader()
        self.cleanAfterMe = removePNG

        self.canWrite = isWriter
Beispiel #4
0
    def __init__(self, isWriter=True, removePNG=True):
        self.view = simple.CreateView('RenderView')
        self.view.Background = [0.0, 0.0, 0.0]
        self.view.CenterAxesVisibility = 0
        self.view.OrientationAxesVisibility = 0

        self.reader = vtkPNGReader()
        self.cleanAfterMe = removePNG

        self.canWrite = isWriter
Beispiel #5
0
def VtkRead(filepath, t):
    if not const.VTK_WARNING:
        log_path = os.path.join(inv_paths.USER_LOG_DIR, "vtkoutput.txt")
        fow = vtkFileOutputWindow()
        fow.SetFileName(log_path.encode(const.FS_ENCODE))
        ow = vtkOutputWindow()
        ow.SetInstance(fow)

    global no_error

    if t == "bmp":
        reader = vtkBMPReader()

    elif t == "tiff" or t == "tif":
        reader = vtkTIFFReader()

    elif t == "png":
        reader = vtkPNGReader()

    elif t == "jpeg" or t == "jpg":
        reader = vtkJPEGReader()

    else:
        return False

    reader.AddObserver("ErrorEvent", VtkErrorToPy)
    reader.SetFileName(filepath)
    reader.Update()

    if no_error:
        image = reader.GetOutput()
        dim = image.GetDimensions()

        if reader.GetNumberOfScalarComponents() > 1:
            luminanceFilter = vtkImageLuminance()
            luminanceFilter.SetInputData(image)
            luminanceFilter.Update()

            image = vtkImageData()
            image.DeepCopy(luminanceFilter.GetOutput())

        img_array = numpy_support.vtk_to_numpy(
            image.GetPointData().GetScalars())
        img_array.shape = (dim[1], dim[0])

        return img_array
    else:
        no_error = True
        return False
Beispiel #6
0
    def __init__(self, directory):
        self.basePath = directory
        self.layers = []
        self.data = []
        self.imageReader = vtkPNGReader()

        # Load JSON metadata
        with open(os.path.join(directory, "config.json"), "r") as f:
            self.config = json.load(f)
            self.nbLayers = len(self.config["scene"])
            while len(self.layers) < self.nbLayers:
                self.layers.append({})

        with open(os.path.join(directory, "index.json"), "r") as f:
            self.info = json.load(f)
Beispiel #7
0
    def __init__(self, directory):
        self.basePath = directory
        self.layers = []
        self.data = []
        self.imageReader = vtkPNGReader()

        # Load JSON metadata
        with open(os.path.join(directory, "config.json"), "r") as f:
            self.config = json.load(f)
            self.nbLayers = len(self.config['scene'])
            while len(self.layers) < self.nbLayers:
                self.layers.append({})

        with open(os.path.join(directory, "index.json"), "r") as f:
            self.info = json.load(f)
Beispiel #8
0
def vtkRegressionTestImage( renWin ):
    """vtkRegressionTestImage(renWin) -- produce regression image for window

    This function writes out a regression .png file for a vtkWindow.
    Does anyone involved in testing care to elaborate?
    """
    from vtkmodules.vtkRenderingCore import vtkWindowToImageFilter
    from vtkmodules.vtkIOImage import vtkPNGReader
    from vtkmodules.vtkImagingCore import vtkImageDifference

    imageIndex=-1;
    for i in range(0, len(sys.argv)):
        if sys.argv[i] == '-V' and i < len(sys.argv)-1:
            imageIndex = i+1

    if imageIndex != -1:
        fname = os.path.join(vtkGetDataRoot(), sys.argv[imageIndex])

        rt_w2if = vtkWindowToImageFilter()
        rt_w2if.SetInput(renWin)

        if os.path.isfile(fname):
            pass
        else:
            rt_pngw = vtkPNGWriter()
            rt_pngw.SetFileName(fname)
            rt_pngw.SetInputConnection(rt_w2if.GetOutputPort())
            rt_pngw.Write()
            rt_pngw = None

        rt_png = vtkPNGReader()
        rt_png.SetFileName(fname)

        rt_id = vtkImageDifference()
        rt_id.SetInputConnection(rt_w2if.GetOutputPort())
        rt_id.SetImageConnection(rt_png.GetOutputPort())
        rt_id.Update()

        if rt_id.GetThresholdedError() <= 10:
            return 1
        else:
            sys.stderr.write('Failed image test: %f\n'
                             % rt_id.GetThresholdedError())
            return 0
    return 2
Beispiel #9
0
def vtkRegressionTestImage(renWin):
    """vtkRegressionTestImage(renWin) -- produce regression image for window

    This function writes out a regression .png file for a vtkWindow.
    Does anyone involved in testing care to elaborate?
    """
    from vtkmodules.vtkRenderingCore import vtkWindowToImageFilter
    from vtkmodules.vtkIOImage import vtkPNGReader
    from vtkmodules.vtkImagingCore import vtkImageDifference

    imageIndex = -1
    for i in range(0, len(sys.argv)):
        if sys.argv[i] == '-V' and i < len(sys.argv) - 1:
            imageIndex = i + 1

    if imageIndex != -1:
        fname = os.path.join(vtkGetDataRoot(), sys.argv[imageIndex])

        rt_w2if = vtkWindowToImageFilter()
        rt_w2if.SetInput(renWin)

        if os.path.isfile(fname):
            pass
        else:
            rt_pngw = vtkPNGWriter()
            rt_pngw.SetFileName(fname)
            rt_pngw.SetInputConnection(rt_w2if.GetOutputPort())
            rt_pngw.Write()
            rt_pngw = None

        rt_png = vtkPNGReader()
        rt_png.SetFileName(fname)

        rt_id = vtkImageDifference()
        rt_id.SetInputConnection(rt_w2if.GetOutputPort())
        rt_id.SetImageConnection(rt_png.GetOutputPort())
        rt_id.Update()

        if rt_id.GetThresholdedError() <= 10:
            return 1
        else:
            sys.stderr.write('Failed image test: %f\n' %
                             rt_id.GetThresholdedError())
            return 0
    return 2
Beispiel #10
0
def convertImageToFloat(srcPngImage, destFile, scalarRange=[0.0, 1.0]):
    reader = vtkPNGReader()
    reader.SetFileName(srcPngImage)
    reader.Update()
    rgbArray = reader.GetOutput().GetPointData().GetArray(0)
    stackSize = rgbArray.GetNumberOfTuples()
    size = reader.GetOutput().GetDimensions()

    outputArray = vtkFloatArray()
    outputArray.SetNumberOfComponents(1)
    outputArray.SetNumberOfTuples(stackSize)

    for idx in range(stackSize):
        outputArray.SetTuple1(
            idx, getScalarFromRGB(rgbArray.GetTuple(idx), scalarRange))

    # Write float file
    with open(destFile, "wb") as f:
        f.write(memoryview(outputArray))

    return size
Beispiel #11
0
def convertImageToFloat(srcPngImage, destFile, scalarRange=[0.0, 1.0]):
    reader = vtkPNGReader()
    reader.SetFileName(srcPngImage)
    reader.Update()
    rgbArray = reader.GetOutput().GetPointData().GetArray(0)
    stackSize = rgbArray.GetNumberOfTuples()
    size = reader.GetOutput().GetDimensions()


    outputArray = vtkFloatArray()
    outputArray.SetNumberOfComponents(1)
    outputArray.SetNumberOfTuples(stackSize)

    for idx in range(stackSize):
        outputArray.SetTuple1(
            idx,
            getScalarFromRGB(rgbArray.GetTuple(idx), scalarRange)
        )

    # Write float file
    with open(destFile, 'wb') as f:
        f.write(buffer(outputArray))

    return size
Beispiel #12
0
    def convert(self, directory):
        imagePaths = {}
        depthPaths = {}
        layerNames = []
        for fileName in os.listdir(directory):
            if "_rgb" in fileName or "_depth" in fileName:
                fileId = fileName.split("_")[0][0]
                if "_rgb" in fileName:
                    imagePaths[fileId] = os.path.join(directory, fileName)
                else:
                    layerNames.append(fileId)
                    depthPaths[fileId] = os.path.join(directory, fileName)

        layerNames.sort()

        if len(layerNames) == 0:
            return

        # Load data in Memory
        depthArrays = []
        imageReader = vtkPNGReader()
        numberOfValues = self.width * self.height * len(layerNames)
        imageSize = self.width * self.height
        self.layers = len(layerNames)

        # Write all images as single memoryview
        opacity = vtkUnsignedCharArray()
        opacity.SetNumberOfComponents(1)
        opacity.SetNumberOfTuples(numberOfValues)

        intensity = vtkUnsignedCharArray()
        intensity.SetNumberOfComponents(1)
        intensity.SetNumberOfTuples(numberOfValues)

        for layer in range(self.layers):
            imageReader.SetFileName(imagePaths[layerNames[layer]])
            imageReader.Update()

            rgbaArray = imageReader.GetOutput().GetPointData().GetArray(0)

            for idx in range(imageSize):
                intensity.SetValue((layer * imageSize) + idx,
                                   rgbaArray.GetValue(idx * 4))
                opacity.SetValue((layer * imageSize) + idx,
                                 rgbaArray.GetValue(idx * 4 + 3))

            with open(depthPaths[layerNames[layer]], "rb") as depthFile:
                depthArrays.append(depthFile.read())

        # Apply pixel sorting
        destOrder = vtkUnsignedCharArray()
        destOrder.SetNumberOfComponents(1)
        destOrder.SetNumberOfTuples(numberOfValues)

        opacityOrder = vtkUnsignedCharArray()
        opacityOrder.SetNumberOfComponents(1)
        opacityOrder.SetNumberOfTuples(numberOfValues)

        intensityOrder = vtkUnsignedCharArray()
        intensityOrder.SetNumberOfComponents(1)
        intensityOrder.SetNumberOfTuples(numberOfValues)

        for pixelIdx in range(imageSize):
            depthStack = []
            for depthArray in depthArrays:
                depthStack.append((depthArray[pixelIdx], len(depthStack)))
            depthStack.sort(key=lambda tup: tup[0])

            for destLayerIdx in range(len(depthStack)):
                sourceLayerIdx = depthStack[destLayerIdx][1]

                # Copy Idx
                destOrder.SetValue((imageSize * destLayerIdx) + pixelIdx,
                                   sourceLayerIdx)
                opacityOrder.SetValue(
                    (imageSize * destLayerIdx) + pixelIdx,
                    opacity.GetValue((imageSize * sourceLayerIdx) + pixelIdx),
                )
                intensityOrder.SetValue(
                    (imageSize * destLayerIdx) + pixelIdx,
                    intensity.GetValue((imageSize * sourceLayerIdx) +
                                       pixelIdx),
                )

        with open(os.path.join(directory, "alpha.uint8"), "wb") as f:
            f.write(memoryview(opacityOrder))

        with open(os.path.join(directory, "intensity.uint8"), "wb") as f:
            f.write(memoryview(intensityOrder))

        with open(os.path.join(directory, "order.uint8"), "wb") as f:
            f.write(memoryview(destOrder))
Beispiel #13
0
    def ShowSlice(self, index=0):
        try:
            dicom = self.dicom_list[index]
        except IndexError:
            dicom = self.dicom_list[0]

        if self.actor is None:
            self.__init_vtk()

        # UPDATE GUI
        ## Text related to size
        value = STR_SIZE % (dicom.image.size[0], dicom.image.size[1])
        self.text_image_size.SetValue(value)

        ## Text related to slice position
        if not (dicom.image.spacing):
            value1 = ''
        else:
            value1 = STR_SPC % (dicom.image.spacing[2])

        if dicom.image.orientation_label == 'AXIAL':
            value2 = STR_LOCAL % (dicom.image.position[2])
        elif dicom.image.orientation_label == 'CORONAL':
            value2 = STR_LOCAL % (dicom.image.position[1])
        elif dicom.image.orientation_label == 'SAGITTAL':
            value2 = STR_LOCAL % (dicom.image.position[0])
        else:
            value2 = ''

        value = "%s\n%s" % (value1, value2)
        self.text_image_location.SetValue(value)

        ## Text related to patient/ acquisiiton data
        value = STR_PATIENT %(dicom.patient.id,\
                              dicom.acquisition.protocol_name)
        self.text_patient.SetValue(value)

        ## Text related to acquisition date and time
        value = STR_ACQ % (dicom.acquisition.date, dicom.acquisition.time)
        self.text_acquisition.SetValue(value)

        if isinstance(dicom.image.thumbnail_path, list):
            reader = vtkPNGReader()
            if _has_win32api:
                reader.SetFileName(
                    win32api.GetShortPathName(
                        dicom.image.thumbnail_path[index]).encode(
                            const.FS_ENCODE))
            else:
                reader.SetFileName(dicom.image.thumbnail_path[index])
            reader.Update()

            image = reader.GetOutput()
        else:
            filename = dicom.image.file
            if _has_win32api:
                filename = win32api.GetShortPathName(filename).encode(
                    const.FS_ENCODE)

            np_image = imagedata_utils.read_dcm_slice_as_np2(filename)
            vtk_image = converters.to_vtk(np_image, dicom.image.spacing, 0,
                                          'AXIAL')

            # ADJUST CONTRAST
            window_level = dicom.image.level
            window_width = dicom.image.window
            colorer = vtkImageMapToWindowLevelColors()
            colorer.SetInputData(vtk_image)
            colorer.SetWindow(float(window_width))
            colorer.SetLevel(float(window_level))
            colorer.Update()

            image = colorer.GetOutput()

        flip = vtkImageFlip()
        flip.SetInputData(image)
        flip.SetFilteredAxis(1)
        flip.FlipAboutOriginOn()
        flip.ReleaseDataFlagOn()
        flip.Update()

        if self.actor is None:
            self.actor = vtkImageActor()
            self.renderer.AddActor(self.actor)

        self.canvas.modified = True

        # PLOT IMAGE INTO VIEWER
        self.actor.SetInputData(flip.GetOutput())
        self.renderer.ResetCamera()
        self.interactor.Render()

        # Setting slider position
        self.slider.SetValue(index)
Beispiel #14
0
def compareImageWithSavedImage(src_img, img_fname, threshold=10):
    """Compares a source image (src_img, which is a vtkImageData) with
    the saved image file whose name is given in the second argument.
    If the image file does not exist the image is generated and
    stored.  If not the source image is compared to that of the
    figure.  This function also handles multiple images and finds the
    best matching image.
    """
    global _NO_IMAGE
    if _NO_IMAGE:
        return

    f_base, f_ext = os.path.splitext(img_fname)

    if not os.path.isfile(img_fname):
        # generate the image
        pngw = vtkPNGWriter()
        pngw.SetFileName(_getTempImagePath(img_fname))
        pngw.SetInputConnection(src_img.GetOutputPort())
        pngw.Write()
        _printCDashImageNotFoundError(img_fname)
        msg = "Missing baseline image: " + img_fname + "\nTest image created: " + _getTempImagePath(img_fname)
        sys.tracebacklimit = 0
        raise RuntimeError(msg)

    pngr = vtkPNGReader()
    pngr.SetFileName(img_fname)
    pngr.Update()

    idiff = vtkImageDifference()
    idiff.SetInputConnection(src_img.GetOutputPort())
    idiff.SetImageConnection(pngr.GetOutputPort())
    idiff.Update()

    min_err = idiff.GetThresholdedError()
    img_err = min_err

    err_index = 0
    count = 0
    if min_err > threshold:
        count = 1
        test_failed = 1
        err_index = -1
        while 1: # keep trying images till we get the best match.
            new_fname = f_base + "_%d.png"%count
            if not os.path.exists(new_fname):
                # no other image exists.
                break
            # since file exists check if it matches.
            pngr.SetFileName(new_fname)
            pngr.Update()
            idiff.Update()
            alt_err = idiff.GetThresholdedError()
            if alt_err < threshold:
                # matched,
                err_index = count
                test_failed = 0
                min_err = alt_err
                img_err = alt_err
                break
            else:
                if alt_err < min_err:
                    # image is a better match.
                    err_index = count
                    min_err = alt_err
                    img_err = alt_err

            count = count + 1
        # closes while loop.

        if test_failed:
            _handleFailedImage(idiff, pngr, img_fname)
            # Print for CDash.
            _printCDashImageError(img_err, err_index, f_base)
            msg = "Failed image test: %f\n"%idiff.GetThresholdedError()
            sys.tracebacklimit = 0
            raise RuntimeError(msg)
    # output the image error even if a test passed
    _printCDashImageSuccess(img_err, err_index)