• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Python compare.compare_images函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中matplotlib.testing.compare.compare_images函数的典型用法代码示例。如果您正苦于以下问题:Python compare_images函数的具体用法?Python compare_images怎么用?Python compare_images使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了compare_images函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_spectogram

 def test_spectogram(self):
     """
     Create spectogram plotting examples in tests/output directory.
     """
     # Create dynamic test_files to avoid dependencies of other modules.
     # set specific seed value such that random numbers are reproduceable
     np.random.seed(815)
     head = {
         'network': 'BW', 'station': 'BGLD',
         'starttime': UTCDateTime(2007, 12, 31, 23, 59, 59, 915000),
         'sampling_rate': 200.0, 'channel': 'EHE'}
     tr = Trace(data=np.random.randint(0, 1000, 824), header=head)
     st = Stream([tr])
     # 1 - using log=True
     with NamedTemporaryFile(suffix='.png') as tf:
         spectrogram.spectrogram(st[0].data, log=True, outfile=tf.name,
                                 samp_rate=st[0].stats.sampling_rate,
                                 show=False)
         # compare images
         expected_image = os.path.join(self.path, 'spectogram_log.png')
         compare_images(tf.name, expected_image, 0.001)
     # 2 - using log=False
     with NamedTemporaryFile(suffix='.png') as tf:
         spectrogram.spectrogram(st[0].data, log=False, outfile=tf.name,
                                 samp_rate=st[0].stats.sampling_rate,
                                 show=False)
         # compare images
         expected_image = os.path.join(self.path, 'spectogram.png')
         compare_images(tf.name, expected_image, 0.001)
开发者ID:miili,项目名称:obspy,代码行数:29,代码来源:test_spectrogram.py


示例2: test_collection

    def test_collection(self):
        """
        Tests to plot beachballs as collection into an existing axis
        object. The moment tensor values are taken form the
        test_Beachball unit test. See that test for more information about
        the parameters.
        """
        mt = [[0.91, -0.89, -0.02, 1.78, -1.55, 0.47],
              [274, 13, 55],
              [130, 79, 98],
              [264.98, 45.00, -159.99],
              [160.55, 76.00, -46.78],
              [1.45, -6.60, 5.14, -2.67, -3.16, 1.36],
              [235, 80, 35],
              [138, 56, 168],
              [1, 1, 1, 0, 0, 0],
              [-1, -1, -1, 0, 0, 0],
              [1, -2, 1, 0, 0, 0],
              [1, -1, 0, 0, 0, 0],
              [1, -1, 0, 0, 0, -1],
              [179, 55, -78],
              [10, 42.5, 90],
              [10, 42.5, 92],
              [150, 87, 1],
              [0.99, -2.00, 1.01, 0.92, 0.48, 0.15],
              [5.24, -6.77, 1.53, 0.81, 1.49, -0.05],
              [16.578, -7.987, -8.592, -5.515, -29.732, 7.517],
              [-2.39, 1.04, 1.35, 0.57, -2.94, -0.94],
              [150, 87, 1]]

        # Initialize figure
        fig = plt.figure(figsize=(6, 6), dpi=300)
        ax = fig.add_subplot(111, aspect='equal')

        # Plot the stations or borders
        ax.plot([-100, -100, 100, 100], [-100, 100, -100, 100], 'rv')

        x = -100
        y = -100
        for i, t in enumerate(mt):
            # add the beachball (a collection of two patches) to the axis
            ax.add_collection(Beach(t, width=30, xy=(x, y), linewidth=.6))
            x += 50
            if (i + 1) % 5 == 0:
                x = -100
                y += 50

        # set the x and y limits and save the output
        ax.axis([-120, 120, -120, 120])
        # create and compare image
        with NamedTemporaryFile(suffix='.png') as tf:
            fig.savefig(tf.name)
            # compare images
            expected_image = os.path.join(self.path, 'bb_collection.png')
            compare_images(tf.name, expected_image, 0.001)
开发者ID:miili,项目名称:obspy,代码行数:55,代码来源:test_beachball.py


示例3: test_contourf_c0p1

def test_contourf_c0p1():
    """
    Test the basic  contour plot
    """
    from matplotlib import pyplot  as plt
    vertices, elements, u = getTestMeshData()
    fig,ax = plt.subplots()
    fem_plt.contourf_c0p1(ax,vertices,elements,u)
    #uncomment this  to generate an image with only the diff "IMAGE ERROR"
    #ax.annotate('IMAGE ERROR', fontsize=22,xy=(0.5, 1.), xytext=(0.5,1.))
    my_dir = os.path.dirname(os.path.realpath(__file__))
    actual = os.path.join(my_dir,"contourf_c0p1.png")
    expected = os.path.join(my_dir,"test_images","contourf_c0p1.png")
    plt.savefig(actual)
    compare_images(expected,actual)
开发者ID:compeco,项目名称:rendering-functions,代码行数:15,代码来源:test_fem_plt.py


示例4: test_plotBenchmark

 def test_plotBenchmark(self):
     """
     Test benchmark plot.
     """
     path = os.path.join(os.path.dirname(__file__), 'data',
                         'seismic01_*_vz.su')
     sufiles = glob.glob(path)
     # new temporary file with PNG extension
     with NamedTemporaryFile(suffix='.png') as tf:
         # generate plot
         plotBenchmark(sufiles, outfile=tf.name, format='PNG')
         # compare images
         expected_image = os.path.join(os.path.dirname(__file__), 'images',
                                       'test_plotBenchmark.png')
         compare_images(tf.name, expected_image, 0.001)
开发者ID:Ciack404,项目名称:obspy,代码行数:15,代码来源:test_benchmark.py


示例5: do_test

                def do_test():
                    figure = plt.figure(fignum)

                    if self._remove_text:
                        self.remove_text(figure)

                    figure.savefig(actual_fname, **self._savefig_kwarg)

                    err = compare_images(expected_fname, actual_fname,
                                         self._tol, in_decorator=True)

                    try:
                        if not os.path.exists(expected_fname):
                            raise ImageComparisonFailure(
                                'image does not exist: %s' % expected_fname)

                        if err:
                            raise ImageComparisonFailure(
                                'images not close: %(actual)s vs. %(expected)s '
                                '(RMS %(rms).3f)'%err)
                    except ImageComparisonFailure:
                        if not check_freetype_version(self._freetype_version):
                            raise KnownFailureTest(
                                "Mismatched version of freetype.  Test requires '%s', you have '%s'" %
                                (self._freetype_version, ft2font.__freetype_version__))
                        raise
开发者ID:AndreLobato,项目名称:matplotlib,代码行数:26,代码来源:decorators.py


示例6: __exit__

    def __exit__(self, exception, *_):
        if exception:
            return

        if self.remove_text:
            _remove_text(self.fig)

        with tempfile.TemporaryDirectory() as tmpdir:
            actual_file = path_from_fixture(self.request, prefix=tmpdir, ext=self.ext)
            actual_filename = str(actual_file)
            if not actual_file.parent.exists():
                actual_file.parent.mkdir(parents=True)
            plt.savefig(actual_filename, **self.savefig_kwargs)

            baseline = path_from_fixture(self.request, prefix='baseline_plots', ext=self.ext)
            baseline_filename = str(baseline)

            if baseline.exists():
                try:
                    data = compare_images(baseline_filename, actual_filename,
                                          self.tol, in_decorator=True)
                except ValueError as exc:
                    if 'could not be broadcast' not in str(exc):
                        raise
                    else:
                        data = dict(actual=actual_filename, expected=baseline_filename)

                self.passed = data is None
                self.report(data)
            else:
                shutil.copyfile(actual_filename, baseline_filename)
                self.passed = True

        plt.close()
        self._exit_style()
开发者ID:haibiao,项目名称:pybinding,代码行数:35,代码来源:compare_figures.py


示例7: test_plot_emsr

    def test_plot_emsr(self):
        # Assess
        p2_0 = 0.046
        p2_1 = 0.556
        p2_2 = 0.673
        points = 40

        native_values = np.random.uniform(3., 8.5, points)
        native_sigmas = np.random.uniform(0.02, 0.2, points)
        target_values = p2_0 + p2_1 * native_values +\
          p2_2 * (native_values ** 2.)
        target_values += np.random.normal(0., 1, points)
        target_sigmas = np.random.uniform(0.025, 0.2, points)
        native_measures = [models.MagnitudeMeasure(
            agency=None, event=None, origin=None,
            scale='Mtest', value=v[0], standard_error=v[1])
            for v in zip(native_values, native_sigmas)]
        target_measures = [models.MagnitudeMeasure(
            agency=None, event=None, origin=None,
            scale='Mtest', value=v[0], standard_error=v[1])
            for v in zip(target_values, target_sigmas)]

        emsr = regression.EmpiricalMagnitudeScalingRelationship(
            native_measures, target_measures)
        emsr.apply_regression_model(regression.LinearModel)
        emsr.apply_regression_model(regression.PolynomialModel,
                                    order=2)

        # Act
        plot(emsr, ACTUAL1)

        # Assert
        self.assertFalse(compare_images(EXPECTED1, ACTUAL1, tol=4))
开发者ID:g-weatherill,项目名称:oq-eqcatalogue-tool,代码行数:33,代码来源:test_plot.py


示例8: test_plotHeatmap_scale_regions

def test_plotHeatmap_scale_regions():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master_scale_reg.mat.gz --outFileName {}".format(ROOT, outfile.name).split()
    deeptools.plotHeatmap.main(args)
    res = compare_images(ROOT + '/master_scale_reg.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:7,代码来源:testskip_heatmapper_images.py


示例9: generate_or_test

    def generate_or_test(self, generate, figure, image, adjust_bbox=True):
        if generate is None:
            result_dir = tempfile.mkdtemp()
            test_image = os.path.abspath(os.path.join(result_dir, image))

            # distutils will put the baseline images in non-accessible places,
            # copy to our tmpdir to be sure to keep them in case of failure
            orig_baseline_image = os.path.abspath(os.path.join(self._baseline_images_dir, image))
            baseline_image = os.path.abspath(os.path.join(result_dir, 'baseline-'+image))
            shutil.copyfile(orig_baseline_image, baseline_image)

            figure.save(test_image)

            if not os.path.exists(baseline_image):
                raise Exception("""Image file not found for comparision test
                                Generated Image:
                                \t{test}
                                This is expected for new tests.""".format(
                                    test=test_image))

            msg = compare_images(baseline_image, test_image, tol=self._tolerance)

            if msg is None:
                shutil.rmtree(result_dir)
            else:
                raise Exception(msg)
        else:
            figure.save(os.path.abspath(os.path.join(generate, image)), adjust_bbox=adjust_bbox)
            pytest.skip("Skipping test, since generating data")
开发者ID:wmwv,项目名称:aplpy,代码行数:29,代码来源:test_images.py


示例10: image_comparison_expect_rms

def image_comparison_expect_rms(im1, im2, tol, expect_rms):
    """Compare two images, expecting a particular RMS error.

    im1 and im2 are filenames relative to the baseline_dir directory.

    tol is the tolerance to pass to compare_images.

    expect_rms is the expected RMS value, or None. If None, the test will
    succeed if compare_images succeeds. Otherwise, the test will succeed if
    compare_images fails and returns an RMS error almost equal to this value.
    """
    im1 = os.path.join(baseline_dir, im1)
    im2_src = os.path.join(baseline_dir, im2)
    im2 = os.path.join(result_dir, im2)
    # Move im2 from baseline_dir to result_dir. This will ensure that
    # compare_images writes the diff file to result_dir, instead of trying to
    # write to the (possibly read-only) baseline_dir.
    shutil.copyfile(im2_src, im2)
    results = compare_images(im1, im2, tol=tol, in_decorator=True)

    if expect_rms is None:
        assert_equal(None, results)
    else:
        assert_not_equal(None, results)
        assert_almost_equal(expect_rms, results['rms'], places=4)
开发者ID:BenFrantzDale,项目名称:matplotlib,代码行数:25,代码来源:test_compare_images.py


示例11: assert_same

    def assert_same(self, tmpdir, tol=0.1):

        os.chdir(tmpdir.strpath)

        expected = tmpdir.join('expected.png').strpath
        script = tmpdir.join('actual.py').strpath
        actual = tmpdir.join('glue_plot.png').strpath

        self.viewer.axes.figure.savefig(expected)

        self.viewer.export_as_script(script)
        subprocess.call([sys.executable, script])

        msg = compare_images(expected, actual, tol=tol)

        if msg:

            from base64 import b64encode

            print("SCRIPT:")
            with open(script, 'r') as f:
                print(f.read())

            print("EXPECTED:")
            with open(expected, 'rb') as f:
                print(b64encode(f.read()).decode())

            print("ACTUAL:")
            with open(actual, 'rb') as f:
                print(b64encode(f.read()).decode())

            pytest.fail(msg, pytrace=False)
开发者ID:glue-viz,项目名称:glue,代码行数:32,代码来源:test_python_export.py


示例12: image_comparison

def image_comparison(original_image_path, figsize=(10, 10), tol=1e-3):
    """
    Context manager that initialize figure that should contain figure
    that should be compared with expected one.

    Parameters
    ----------
    original_image_path : str
        Path to original image that will use for comparison.
    figsize : tuple
        Figure size. Defaults to ``(10, 10)``.
    tol : float
        Comparison tolerance. Defaults to ``1e-3``.

    Raises
    ------
    AssertionError
        Exception would be trigger in case when generated images and
        original one are different.
    """
    currentdir = os.path.abspath(os.path.dirname(__file__))
    original_image_path = os.path.join(currentdir, original_image_path)

    with tempfile.NamedTemporaryFile(suffix='.png') as f:
        figure = plt.figure(figsize=figsize)

        yield figure

        figure.savefig(f.name)
        error = compare_images(f.name, original_image_path, tol=tol)

        if error:
            raise AssertionError("Image comparison failed. \n"
                                 "Information: {}".format(error))
开发者ID:itdxer,项目名称:neupy,代码行数:34,代码来源:utils.py


示例13: test_plotHeatmap_interpolation

def test_plotHeatmap_interpolation():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/large_matrix.mat.gz --interpolation bilinear " \
           "--outFileName {}".format(ROOT, outfile.name).split()
    deeptools.plotHeatmap.main(args)
    res = compare_images(ROOT + '/heatmap_master_interpolation_bilinear.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例14: test_plotHeatmap_multiple_colormap_no_boxes

def test_plotHeatmap_multiple_colormap_no_boxes():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master_multi.mat.gz --colorMap Reds binary terrain --boxAroundHeatmaps no " \
           "--outFileName {}".format(ROOT, outfile.name).split()
    deeptools.plotHeatmap.main(args)
    res = compare_images(ROOT + '/heatmap_master_multi_colormap_no_box.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例15: test_plotHeatmap_multi_bigwig_pergroup

def test_plotHeatmap_multi_bigwig_pergroup():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master_multi.mat.gz --perGroup --samplesLabel file1 file2 file3 file4 " \
           "--outFileName {}".format(ROOT, outfile.name).split()
    deeptools.plotHeatmap.main(args)
    res = compare_images(ROOT + '/heatmap_master_multi_pergroup.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例16: test_plotProfiler_multibigwig

def test_plotProfiler_multibigwig():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master_multi.mat.gz --outFileName {} " \
           "--numPlotsPerRow 2 --yMax 1.5".format(ROOT, outfile.name).split()
    deeptools.plotProfile.main(args)
    res = compare_images(ROOT + '/profile_master_multi.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例17: test_plotProfiler_overlapped_lines

def test_plotProfiler_overlapped_lines():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master.mat.gz --outFileName {} " \
           "--plotType overlapped_lines --yMin -1".format(ROOT, outfile.name).split()
    deeptools.plotProfile.main(args)
    res = compare_images(ROOT + '/profile_master_overlap_lines.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例18: test_plotProfiler

def test_plotProfiler():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master.mat.gz --outFileName {} --regionsLabel uno dos " \
           "--plotType std".format(ROOT, outfile.name).split()
    deeptools.plotProfile.main(args)
    res = compare_images(ROOT + '/profile_master.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例19: test_plotHeatmap_multiple_colors_muti_scales

def test_plotHeatmap_multiple_colors_muti_scales():
    outfile = NamedTemporaryFile(suffix='.png', prefix='plotHeatmap_test_', delete=False)
    args = "-m {}/master_multi.mat.gz --colorList white,blue white,red --zMin 1 0 --zMax 4 5 " \
           "--outFileName {}".format(ROOT, outfile.name).split()
    deeptools.plotHeatmap.main(args)
    res = compare_images(ROOT + '/heatmap_master_multi_color.png', outfile.name, tolerance)
    assert res is None, res
    os.remove(outfile.name)
开发者ID:fidelram,项目名称:deepTools,代码行数:8,代码来源:testskip_heatmapper_images.py


示例20: check_graphic

    def check_graphic(self, tol=_DEFAULT_IMAGE_TOLERANCE):
        """Checks the CRC matches for the current matplotlib.pyplot figure, and closes the figure."""

        unique_id = self._unique_id()

        figure = plt.gcf()

        try:
            expected_fname = os.path.join(os.path.dirname(__file__),
                                          'results', 'visual_tests',
                                          unique_id + '.png')

            if not os.path.isdir(os.path.dirname(expected_fname)):
                os.makedirs(os.path.dirname(expected_fname))

            #: The path where the images generated by the tests should go.
            image_output_directory = os.path.join(os.path.dirname(__file__),
                                                  'result_image_comparison')
            if not os.access(image_output_directory, os.W_OK):
                if not os.access(os.getcwd(), os.W_OK):
                    raise IOError('Write access to a local disk is required '
                                  'to run image tests.  Run the tests from a '
                                  'current working directory you have write '
                                  'access to to avoid this issue.')
                else:
                    image_output_directory = os.path.join(
                        os.getcwd(), 'iris_image_test_output')
            result_fname = os.path.join(image_output_directory,
                                        'result-' + unique_id + '.png')

            if not os.path.isdir(os.path.dirname(result_fname)):
                # Handle race-condition where the directories are
                # created sometime between the check above and the
                # creation attempt below.
                try:
                    os.makedirs(os.path.dirname(result_fname))
                except OSError as err:
                    # Don't care about "File exists"
                    if err.errno != 17:
                        raise

            figure.savefig(result_fname)

            if not os.path.exists(expected_fname):
                warnings.warn('Created image for test %s' % unique_id)
                shutil.copy2(result_fname, expected_fname)

            err = mcompare.compare_images(expected_fname, result_fname, tol=tol)

            if _DISPLAY_FIGURES:
                if err:
                    print('Image comparison would have failed. Message: %s' % err)
                plt.show()
            else:
                assert not err, 'Image comparison failed. Message: %s' % err

        finally:
            plt.close()
开发者ID:agbutteriss,项目名称:iris,代码行数:58,代码来源:__init__.py



注:本文中的matplotlib.testing.compare.compare_images函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python determinism._determinism_check函数代码示例发布时间:2022-05-27
下一篇:
Python compare.comparable_formats函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap