【案例详解-带完整源码】C#通过调用python生成热力图

本文详细介绍了如何使用C#通过调用Python脚本来生成二维数组的热力图。C#端负责数据传递,而Python端利用其丰富的可视化库完成热力图的绘制。案例提供完整源码,并附带了Python环境,便于读者直接运行和调试。
摘要由CSDN通过智能技术生成

效果

将二维数组
在这里插入图片描述
转为热力图:在这里插入图片描述

方法

由于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

源码具体调试步骤

【案例详解-带完整源码】C#通过调用python生成热力图-工程调试

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FarryNiu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值