遇到的问题
python版本3.8.8
在测试scipy.signal.correlate2d函数的时候,跑官网的demo,结果绘图是一闪而过。函数链接:https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.correlate2d.html#scipy.signal.correlate2d
测试代码
Use 2D cross-correlation to find the location of a template in a noisy image:
用2D 互相关在噪声图像中找到模板位置
from scipy import signal
from scipy import misc
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
face = misc.face(gray=True) - misc.face(gray=True).mean()
template = np.copy(face[300:365, 670:750]) # right eye
template -= template.mean()
face = face + np.random.randn(*face.shape) * 50 # add noise
corr = signal.correlate2d(face, template, boundary='symm', mode='same')
y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match
fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1,
figsize=(6, 15))
ax_orig.imshow(face, cmap='gray')
ax_orig.set_title('Original')
ax_orig.set_axis_off()
ax_template.imshow(template, cmap='gray')
ax_template.set_title('Template')
ax_template.set_axis_off()
ax_corr.imshow(corr, cmap='gray')
ax_corr.set_title('Cross-correlation')
ax_corr.set_axis_off()
ax_orig.plot(x, y, 'ro')
fig.show()
解决方法
做法
法一:在fig.show()后面加上一句:
input()
这样需要输入回车才会结束。
法二:
弃用最后的fig.show(),改用:
plt.show()
上述两种方法都可以解决画图一闪而过的问题。
得到了官网相同的图:
解释
对上面的老哥表示感谢,详见参考1.
其实fig.show()可以用于IPython。在IPython环境下,调用plt.show()是不能显示出绘制的图像的,但是调用fig.show()就可以显示出图像。
详见参考2
参考
[1]https://github.com/matplotlib/matplotlib/issues/13101
[2]https://eliasyin.com/2020/03/15/fig-show-%E4%B8%8E-plt-show/