本文整理汇总了Python中matplotlib.testing.compare.compare_images函数的典型用法代码示例。如果您正苦于以下问题:Python compare_images函数的具体用法?Python compare_images怎么用?Python compare_images使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了compare_images函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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)
示例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)
示例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)
示例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
示例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()
示例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))
示例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)
示例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")
示例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)
示例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)
示例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))
示例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)
示例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)
示例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)