def testImportExport(self):
        "Testing if images can be imported to and from numeric arrays."
        imp = vtkImageImportFromArray()
        exp = vtkImageExportToArray()
        idiff = vtk.vtkImageDifference()

        img_dir = Testing.getAbsImagePath("")
        for i in glob.glob(os.path.join(img_dir, "*.png")):
            # Putting the reader outside the loop causes bad problems.
            reader = vtk.vtkPNGReader()
            reader.SetFileName(i)
            reader.Update()

            # convert the image to a Numeric Array and convert it back
            # to an image data.
            exp.SetInputConnection(reader.GetOutputPort())
            imp.SetArray(exp.GetArray())

            # ensure there is no difference between orig image and the
            # one we converted and un-converted.
            idiff.SetInputConnection(imp.GetOutputPort())
            idiff.SetImage(reader.GetOutput())
            idiff.Update()
            err = idiff.GetThresholdedError()

            msg = "Test failed on image %s, with threshold "\
                  "error: %d"%(i, err)
            self.assertEqual(err, 0.0, msg)
    def testImportExport(self):
        "Testing if images can be imported to and from numeric arrays."
        imp = vtkImageImportFromArray()
        exp = vtkImageExportToArray()
        idiff = vtk.vtkImageDifference()        

        img_dir = Testing.getAbsImagePath("")
        for i in glob.glob(os.path.join(img_dir, "*.png")):
            # Putting the reader outside the loop causes bad problems.
            reader = vtk.vtkPNGReader()            
            reader.SetFileName(i)
            reader.Update()

            # convert the image to a Numeric Array and convert it back
            # to an image data.            
            exp.SetInputConnection(reader.GetOutputPort())
            imp.SetArray(exp.GetArray())

            # ensure there is no difference between orig image and the
            # one we converted and un-converted.            
            idiff.SetInputConnection(imp.GetOutputPort())
            idiff.SetImage(reader.GetOutput())
            idiff.Update()
            err = idiff.GetThresholdedError()

            msg = "Test failed on image %s, with threshold "\
                  "error: %d"%(i, err)
            self.assertEqual(err, 0.0, msg)
示例#3
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkImageDifference(), 'Processing.',
         ('vtkImageData', 'vtkImageData'), ('vtkImageData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
示例#4
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkImageDifference(),
                                       'Processing.',
                                       ('vtkImageData', 'vtkImageData'),
                                       ('vtkImageData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
示例#5
0
    def compare_png_images(self,
                           image1_filename,
                           image2_filename,
                           threshold=16,
                           allow_shift=False):
        """Compare two PNG images on disc.  No two pixels may differ with more
        than the default threshold.
        """

        import vtk

        r1 = vtk.vtkPNGReader()
        r1.SetFileName(image1_filename)
        r1.Update()

        r2 = vtk.vtkPNGReader()
        r2.SetFileName(image2_filename)
        r2.Update()

        # there's a bug in VTK 5.0.1 where input images of unequal size
        # (depending on which input is larger) will cause a segfault
        # see http://www.vtk.org/Bug/bug.php?op=show&bugid=3586
        # se we check for that situation and bail if it's the case
        if r1.GetOutput().GetDimensions() != r2.GetOutput().GetDimensions():
            em = 'Input images %s and %s are not of equal size.' % \
                 (image1_filename, image2_filename)
            raise RuntimeError, em

        # sometimes PNG files have an ALPHA component we have to chuck away
        # do this for both images
        ec1 = vtk.vtkImageExtractComponents()
        ec1.SetComponents(0, 1, 2)
        ec1.SetInput(r1.GetOutput())

        ec2 = vtk.vtkImageExtractComponents()
        ec2.SetComponents(0, 1, 2)
        ec2.SetInput(r2.GetOutput())

        idiff = vtk.vtkImageDifference()
        idiff.SetThreshold(threshold)

        if allow_shift:
            idiff.AllowShiftOn()
        else:
            idiff.AllowShiftOff()

        idiff.SetImage(ec1.GetOutput())
        idiff.SetInputConnection(ec2.GetOutputPort())

        idiff.Update()

        return idiff.GetThresholdedError()
示例#6
0
    def compare_png_images(self, image1_filename, image2_filename,
                           threshold=16, allow_shift=False):

        """Compare two PNG images on disc.  No two pixels may differ with more
        than the default threshold.
        """

        import vtk

        r1 = vtk.vtkPNGReader()
        r1.SetFileName(image1_filename)
        r1.Update()
        
        r2 = vtk.vtkPNGReader()
        r2.SetFileName(image2_filename)
        r2.Update()

        # there's a bug in VTK 5.0.1 where input images of unequal size
        # (depending on which input is larger) will cause a segfault
        # see http://www.vtk.org/Bug/bug.php?op=show&bugid=3586
        # se we check for that situation and bail if it's the case
        if r1.GetOutput().GetDimensions() != r2.GetOutput().GetDimensions():
            em = 'Input images %s and %s are not of equal size.' % \
                 (image1_filename, image2_filename)
            raise RuntimeError, em

        # sometimes PNG files have an ALPHA component we have to chuck away
        # do this for both images
        ec1 = vtk.vtkImageExtractComponents()
        ec1.SetComponents(0,1,2)
        ec1.SetInput(r1.GetOutput())
        
        ec2 = vtk.vtkImageExtractComponents()
        ec2.SetComponents(0,1,2)
        ec2.SetInput(r2.GetOutput())

        idiff = vtk.vtkImageDifference()
        idiff.SetThreshold(threshold)

        if allow_shift:
            idiff.AllowShiftOn()
        else:
            idiff.AllowShiftOff()

        idiff.SetImage(ec1.GetOutput())
        idiff.SetInputConnection(ec2.GetOutputPort())

        idiff.Update()

        return idiff.GetThresholdedError()
示例#7
0
 def compare_thumbnails(prev, next):
     #vtkImageDifference assumes RGB, so strip alpha
     def removeAlpha(file):
         freader = vtk.vtkPNGReader()
         freader.SetFileName(file)
         removealpha = vtk.vtkImageExtractComponents()
         removealpha.SetComponents(0,1,2)
         removealpha.SetInputConnection(freader.GetOutputPort())
         removealpha.Update()
         return removealpha.GetOutput()
     #do the image comparison
     a = removeAlpha(prev)
     b = removeAlpha(next)
     idiff = vtk.vtkImageDifference()
     idiff.SetInput(a)
     idiff.SetImage(b)
     idiff.Update()
     return idiff.GetThresholdedError()
示例#8
0
def test_example(tmp_path):
    os.chdir(tmp_path)
    assets = Path(__file__).parent / 'assets'
    for f in [
            "example.xyz", "example.settings", "example.commands",
            "example.iso"
    ]:
        shutil.copy(assets / f, f)

    ref_reader = vtk.vtkPNGReader()
    ref_reader.SetFileName(str(assets / "example.png"))
    ref_reader.Update()
    ref_img = vtk.vtkImageExtractComponents()
    ref_img.SetComponents(0, 1, 2)
    ref_img.SetInputConnection(ref_reader.GetOutputPort())
    ref_img.Update()

    p = subprocess.Popen([
        'dap', '-e', 'read example.settings', '-e', 'read example.commands',
        '-e', 'view -dir 1 0.1 0.2  0 0 1', 'example.xyz'
    ],
                         stdin=subprocess.PIPE,
                         stdout=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    out, err = p.communicate('snapshot test.png\nexit\n'.encode())
    assert p.returncode == 0

    test_reader = vtk.vtkPNGReader()
    test_reader.SetFileName("test.png")
    test_reader.Update()
    test_img = vtk.vtkImageExtractComponents()
    test_img.SetComponents(0, 1, 2)
    test_img.SetInputConnection(test_reader.GetOutputPort())
    test_img.Update()

    idiff = vtk.vtkImageDifference()
    # idiff.SetThreshold(1)
    idiff.AllowShiftOff()
    idiff.SetImageData(ref_img.GetOutput())
    idiff.SetInputConnection(test_img.GetOutputPort())
    idiff.Update()

    # print("thresh error", idiff.GetThresholdedError())
    assert idiff.GetError() < 1.0e-10
示例#9
0
    def compare_thumbnails(prev, next):
        #vtkImageDifference assumes RGB, so strip alpha
        def removeAlpha(file):
            freader = vtk.vtkPNGReader()
            freader.SetFileName(file)
            removealpha = vtk.vtkImageExtractComponents()
            removealpha.SetComponents(0, 1, 2)
            removealpha.SetInputConnection(freader.GetOutputPort())
            removealpha.Update()
            return removealpha.GetOutput()

        #do the image comparison
        a = removeAlpha(prev)
        b = removeAlpha(next)
        idiff = vtk.vtkImageDifference()
        idiff.SetInput(a)
        idiff.SetImage(b)
        idiff.Update()
        return idiff.GetThresholdedError()
示例#10
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?
    """
    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 = vtk.vtkWindowToImageFilter()
        rt_w2if.SetInput(renWin)

        if os.path.isfile(fname):
            pass
        else:
            rt_pngw = vtk.vtkPNGWriter()
            rt_pngw.SetFileName(fname)
            rt_pngw.SetInput(rt_w2if.GetOutput())
            rt_pngw.Write()
            rt_pngw = None

        rt_png = vtk.vtkPNGReader()
        rt_png.SetFileName(fname)

        rt_id = vtk.vtkImageDifference()
        rt_id.SetInput(rt_w2if.GetOutput())
        rt_id.SetImage(rt_png.GetOutput())
        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
            
示例#11
0
文件: misc.py 项目: 151706061/VTK
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?
    """
    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 = vtk.vtkWindowToImageFilter()
        rt_w2if.SetInput(renWin)

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

        rt_png = vtk.vtkPNGReader()
        rt_png.SetFileName(fname)

        rt_id = vtk.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
示例#12
0
def compare_screenshots(png0, png1, threshold):
    # load the two input images
    img0 = vtk.vtkPNGReader()
    img0.SetFileName(png0)
    img0.Update()

    img1 = vtk.vtkPNGReader()
    img1.SetFileName(png1)
    img1.Update()

    # compare the two images
    imdiff = vtk.vtkImageDifference()
    imdiff.SetInputConnection(img0.GetOutputPort())
    imdiff.SetImageConnection(img1.GetOutputPort())
    imdiff.Update()

    err = round(imdiff.GetThresholdedError(), 3)

    if err > threshold:
        return (False, err)

    return (True, err)
示例#13
0
文件: Testing.py 项目: neuzhong/VTK
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 = vtk.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 = vtk.vtkPNGReader()
    pngr.SetFileName(img_fname)
    pngr.Update()

    idiff = vtk.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)
示例#14
0
def image_compare(testImage, baselineImage):
    imageDiff = vtk.vtkImageDifference()
    imageDiff.SetInputData(testImage)
    imageDiff.SetImageData(baselineImage)
    imageDiff.Update()
    return (imageDiff.GetThresholdedError(), imageDiff.GetOutput())
示例#15
0
def image_compare(testImage, baselineImage):
    imageDiff = vtk.vtkImageDifference()
    imageDiff.SetInputData(testImage)
    imageDiff.SetImageData(baselineImage)
    imageDiff.Update()
    return (imageDiff.GetThresholdedError(), imageDiff.GetOutput())
示例#16
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 = vtk.vtkPNGWriter()
        pngw.SetFileName(_getTempImagePath(img_fname))
        pngw.SetInput(src_img)
        pngw.Write()
        return 
        
    pngr = vtk.vtkPNGReader()
    pngr.SetFileName(img_fname)

    idiff = vtk.vtkImageDifference()
    idiff.SetInput(src_img)
    idiff.SetImage(pngr.GetOutput())
    idiff.Update()

    min_err = idiff.GetThresholdedError()
    img_err = min_err
    best_img = img_fname

    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
                best_img = new_fname
                break
            else:
                if alt_err < min_err:
                    # image is a better match.
                    err_index = count
                    min_err = alt_err
                    img_err = alt_err
                    best_img = new_fname

            count = count + 1
        # closes while loop.

        if test_failed:
            _handleFailedImage(idiff, pngr, best_img)
            # Print for Dart.
            _printDartImageError(img_err, err_index, f_base)
            msg = "Failed image test: %f\n"%idiff.GetThresholdedError()
            raise AssertionError, msg
    # output the image error even if a test passed
    _printDartImageSuccess(img_err, err_index)
示例#17
0
def compare_images(im1, im2, threshold=1, use_vtk=True):
    """Compare two different images of the same size.

    Parameters
    ----------
    im1 : filename, np.ndarray, vtkRenderWindow, or vtkImageData
        Render window, numpy array representing the output of a render
        window, or ``vtkImageData``

    im2 : filename, np.ndarray, vtkRenderWindow, or vtkImageData
        Render window, numpy array representing the output of a render
        window, or ``vtkImageData``

    threshold : int
        Threshold tolerance for pixel differences.  This should be
        greater than 0, otherwise it will always return an error, even
        on identical images.

    use_vtk : bool
        When disabled, computes the mean pixel error over the entire
        image using numpy.  The difference between pixel is calculated
        for each RGB channel, summed, and then divided by the number
        of pixels.  This is faster than using
        ``vtk.vtkImageDifference`` but potentially less accurate.

    Returns
    -------
    error : float
        Total error between the images if using ``use_vtk=True``, and
        the mean pixel error when ``use_vtk=False``.

    Examples
    --------
    Compare two active plotters

    >>> import pyvista
    >>> pl1 = pyvista.Plotter()
    >>> _ = pl1.add_mesh(pyvista.Sphere(), smooth_shading=True)
    >>> pl2 = pyvista.Plotter()
    >>> _ = pl2.add_mesh(pyvista.Sphere(), smooth_shading=False)
    >>> pyvista.compare_images(pl1, pl2)  # doctest:+SKIP

    Compare two active plotters

    >>> import pyvista
    >>> img1 = pyvista.read('img1.png')  # doctest:+SKIP
    >>> img2 = pyvista.read('img2.png')  # doctest:+SKIP
    >>> pyvista.compare_images(img1, img2)  # doctest:+SKIP

    """
    from pyvista import wrap, UniformGrid, read, Plotter

    def to_img(img):
        if isinstance(img, UniformGrid):  # pragma: no cover
            return img
        elif isinstance(img, vtk.vtkImageData):
            return wrap(img)
        elif isinstance(img, str):
            return read(img)
        elif isinstance(img, np.ndarray):
            return wrap_image_array(img)
        elif isinstance(img, Plotter):
            if img._first_time:  # must be rendered first else segfault
                img._on_first_render_request()
                img.render()
            return image_from_window(img.ren_win, True, ignore_alpha=True)
        else:
            raise TypeError(
                f'Unsupported data type {type(img)}.  Should be '
                'Either a np.ndarray, vtkRenderWindow, or vtkImageData')

    im1 = remove_alpha(to_img(im1))
    im2 = remove_alpha(to_img(im2))

    if im1.GetDimensions() != im2.GetDimensions():
        raise RuntimeError('Input images %s and %s are not of equal size.')

    if use_vtk:
        img_diff = vtk.vtkImageDifference()
        img_diff.SetThreshold(threshold)
        img_diff.SetInputData(im1)
        img_diff.SetImageData(im2)
        img_diff.AllowShiftOff()  # vastly increases compute time when enabled
        # img_diff.AveragingOff()  # increases compute time
        img_diff.Update()
        return img_diff.GetError()

    # otherwise, simply compute the mean pixel difference
    diff = np.abs(im1.point_arrays[0] - im2.point_arrays[0])
    return np.sum(diff) / im1.point_arrays[0].shape[0]
示例#18
0
from vtk.util.vtkImageExportToArray import vtkImageExportToArray
from vtk.util.vtkImageImportFromArray import vtkImageImportFromArray


img1 = sys.argv[1]
img2 = sys.argv[2]

def setupReader(img):
    rd = vtk.vtkPNGReader()
    rd.SetFileName(img1)
    rd.Update()
    imp = vtkImageImportFromArray()
    exp = vtkImageExportToArray()
    exp.SetInputConnection(rd.GetOutputPort())
    imp.SetArray(exp.GetArray())
    return imp


rd1 = setupReader(img1)
rd2 = setupReader(img2)

idiff = vtk.vtkImageDifference()
idiff.SetInputConnection(rd2.GetOutputPort())
idiff.SetImageConnection(rd1.GetOutputPort())
idiff.Update()

err = idiff.GetThresholdedError()

print "Diff:",err