我正在尝试调整此链接中接受的答案代码以达到我的目的:使用 plt 在热图上绘制渐变箭头
我正在从事一个项目,该项目要求我以 .csv 文件的形式拍摄热图像,然后从 .csv 文件中获取数据以制作箭头(通过 quiverplot streamplot 等)来显示热流的方向从图像上的最热点(最高像素值)开始。我认为这可以使用图像的渐变来实现,但我不确定如何实现。
这是我的代码:
import matplotlib.pyplot as plt
import numpy as np
import math
directory = os.chdir(r'user_directory') #Set folder to look in
file = 'data.csv'
data = np.genfromtxt(file, delimiter = ',')
horizontal_min, horizontal_max, horizontal_stepsize = 0, 100, 0.3
vertical_min, vertical_max, vertical_stepsize = 0, 100, 0.5
horizontal_dist = horizontal_max-horizontal_min
vertical_dist = vertical_max-vertical_min
horizontal_stepsize = horizontal_dist / float(math.ceil(horizontal_dist/float(horizontal_stepsize)))
vertical_stepsize = vertical_dist / float(math.ceil(vertical_dist/float(vertical_stepsize)))
xv, yv = np.meshgrid(np.arange(horizontal_min, horizontal_max, horizontal_stepsize),
np.arange(vertical_min, vertical_max, vertical_stepsize))
xv+=horizontal_stepsize/2.0
yv+=vertical_stepsize/2.0
result_matrix = np.asmatrix(data)
yd, xd = np.gradient(result_matrix)
def func_to_vectorize(x, y, dx, dy, scaling=0.01):
plt.arrow(x, y, dx*scaling, dy*scaling), fc="k", ec="k", head_width=0.06,
head_length=0.1)
vectorized_arrow_drawing = np.vectorize(func_to_vectorize)
plt.imshow(np.flip(result_matrix,0), extent=[horizontal_min, horizontal_max, vertical_min,
vertical_max])
vectorized_arrow_drawing(xv, yv, xd, yd, 0.1)
plt.colorbar()
plt.show()
这是我得到的错误:
ValueError: operands could not be broadcast together with shapes (200,335) (200,335) (100,100) (100,100) ()
EDIT: Traceback Error
ValueError Traceback (most recent call last)
<ipython-input-95-25a8b7e2dff8> in <module>
46
47 plt.imshow(np.flip(result_matrix,0), extent=[horizontal_min,
horizontal_max, vertical_min, vertical_max])
---> 48 vectorized_arrow_drawing(xv, yv, xd, yd, 0.1)
49 plt.colorbar()
50 plt.show()
~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in __call__(self,
*args, **kwargs)
1970 vargs.extend([kwargs[_n] for _n in names])
1971
-> 1972 return self._vectorize_call(func=func, args=vargs)
1973
1974 def _get_ufunc_and_otypes(self, func, args):
~\Anaconda3\lib\site-packages\numpy\lib\function_base.py in
_vectorize_call(self, func, args)
2046 for a in args]
2047
-> 2048 outputs = ufunc(*inputs)
2049
2050 if ufunc.nout == 1:
ValueError: operands could not be broadcast together with shapes (100,168)
(100,168) (100,100) (100,100) ()
你真的需要xd, yd, xv, yv
所有的都具有相同的形状(或者都可以广播到相同的形状,但在功能上这是一样的)vectorize
才能工作。最简单的方法是:
xv, yv = np.meshgrid(np.linspace(horizontal_min, horizontal_max, data.shape[0]),
np.linspace(vertical_min, vertical_max, data.shape[1]))
如果你真的想在比另一个方向多分辨率的另一种方法是利用scipy.interpolate.interp2d
内插xd
和yd
对尺寸xv
和yv
。但这要复杂得多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句