本例子实现的功能是:

       根据stat.npy、ops.npy两个npy文件的内容,显示图形

1. 用python代码实现读取两个文件,文件名为read_npy.py,代码如下:

import numpy as np

def read_npy_files(stat_file, ops_file):
    stat = np.load(stat_file, allow_pickle=True)
    ops = np.load(ops_file, allow_pickle=True).item()
    return stat, ops

2. 在c#代码里,先设置python环境,再得到两个数组,最后根据数组显示图像,c#代码如下:

 int ncells = 46;
 // 设置 Python 虚拟环境的路径
 string pathToVirtualEnv = @"D:\ProgramData\anaconda3\suite2p";
 Environment.SetEnvironmentVariable("PATH", pathToVirtualEnv, EnvironmentVariableTarget.Process);
 Environment.SetEnvironmentVariable("PYTHONHOME", pathToVirtualEnv, EnvironmentVariableTarget.Process);
 Environment.SetEnvironmentVariable("PYTHONPATH", $"{pathToVirtualEnv}\\Lib\\site-packages;{pathToVirtualEnv}\\Lib", EnvironmentVariableTarget.Process);
 // 设置 Python DLL 的路径
 Runtime.PythonDLL = @"D:\ProgramData\anaconda3\suite2p\python39.dll";
 PythonEngine.PythonHome = pathToVirtualEnv;
 PythonEngine.PythonPath = PythonEngine.PythonPath + ";" + Environment.GetEnvironmentVariable("PYTHONPATH", EnvironmentVariableTarget.Process);
 PythonEngine.Initialize();

 // 读取 .npy 文件
 dynamic read_npy = Py.Import("read_npy");

 using (Py.GIL())
 {
     var result = read_npy.read_npy_files("stat.npy", "ops.npy");
     var stat = result[0];
     var ops = result[1];

     int Ly = Convert.ToInt32(ops["Ly"].ToString());
     int Lx = Convert.ToInt32(ops["Lx"].ToString());

     // 创建一个空图像
     var im = np.zeros(new Shape(Ly, Lx));

     for (int n = 0; n < ncells; n++)
     {
         var ypix = stat[n]["ypix"];
         var xpix = stat[n]["xpix"];
         var overlap = stat[n]["overlap"];

         for (int i = 0; i < (int)ypix.shape[0]; i++)
         {
             if (!Convert.ToBoolean(overlap[i].ToString()))
             {
                 im[ypix[i].ToString(), xpix[i].ToString()] = n + 1;
             }
         }
     }

     // 将 NumSharp 的 NDArray 转换为 OpenCvSharp 的 Mat
     float[] imData = im.astype(np.float32).ToArray<float>();
     Mat imMat = new Mat(Ly, Lx, MatType.CV_32F);
     imMat.SetArray(imData);
     
     // 显示图像
     Cv2.ImShow("Image", imMat);
 }

 // 关闭 Python 引擎
 PythonEngine.Shutdown();

3. 运行后的结果如下:

c#调用python代码,实现读取npy的数据并显示图像-LMLPHP

完整的代码如下:

https://download.csdn.net/download/orangapple/89598350

07-31 14:37