效果
将二维数组
转为热力图:
方法
由于C#没有方便的热力图工具,因此可以调用python程序来生成热力图
C#端
// array为热力图的源二维数组
double[,] array = new double[3, 4] { { 5.4, 5.5, 5.3, 5.4 }, { 5.2, 5.1, 5, 5 }, { 5.5, 6, 6.7, 6.8 } };
// 获取array的行数和列数
int row = array.GetLength(0);
int col = array.GetLength(1);
// 调用外部python
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "./python3.6/python3.6.exe";
p.StartInfo.CreateNoWindow = true;
// 拼接调用python的参数:行数 列数 数据[0][1] 数据[0][2] ... ... 数据[row][col]
String inf = "";
inf += row + " ";
inf += col;
foreach (double i in array)
{
inf += " " + i;
}
Console.WriteLine(inf);
// 调用python执行t.py
p.StartInfo.Arguments = string.Format("{0} {1}", "t.py", inf);
p.StartInfo.RedirectStandardInput = true;
p.Start();
string output = p.StandardOutput.ReadToEnd();
Console.WriteLine(output);
p.WaitForExit();
// 在t.py中会生成热力图hotmap.jpg,读取并展示它
fileStream = new FileStream("./hotmap.jpg", FileMode.Open, FileAccess.Read);
pictureBox1.Image = Image.FromStream(fileStream);
//关闭流
fileStream.Close();
//销毁流对象
fileStream.Dispose();
python端
import numpy as np
import seaborn as sns
import sys
a = sys.argv
# a为输入参数
print(a)
# 读取行列数
w = int(a[1])
h = int(a[2])
# 恢复二维数组
arr = np.zeros([w,h])
cnt = 3
for i in range(0,w):
for j in range(0,h):
arr[i][j] = float(a[cnt])
cnt = cnt + 1
# 生成热力图
sns.set_theme()
uniform_data = arr
ax = sns.heatmap(uniform_data)
# 保存热力图
ax.figure.savefig('./hotmap.jpg')
注意事项
本案例中附带了一个Python3.6 amd64,因此不用手动安装python,python在开发时放在debug目录下
源码
csdn资源:https://download.csdn.net/download/qq_43474959/86242537