c#实现CSV数据转换Halcon图像

该代码示例读取CSV文件中的点云Z值数据,通过C#处理并生成实型图像。首先读取文件,解析行和列,分配内存,然后填充数据到数组,再将数组数据拷贝到内存,最后使用HalconDotNet库生成图像并保存为TIFF格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要

CSV文件中保存有点云Z值数据,将文件数据读取出,将生成实型图像。

读取文件

读取文件中的所有行为字符串,并按分割符,分析数据,推理出应该的图像长和宽。申请对应的数组和内内存指针。

 string[] lines = File.ReadAllLines(fileName);
 int w = lines[0].Split(',').Length;
 int h = lines.Length;
 float[] arr = new float[w * h];
 if (ptr == IntPtr.Zero)
 {
      ptr = Marshal.AllocHGlobal(arr.Length * sizeof(float));
 }

 填充数据到数组中

 for (int i = 0; i < lines.Length; i++)
  {
              
    Console.WriteLine("{0}%", (i * 1.0 / lines.Length * 100).ToString("00"));
    string[] strs = lines[i].Split(',');
    for (int j = 0; j < w; j++)
    {
       arr[i * w + j] = (float)Convert.ToDouble(strs[j]);
     }
  }

将数组中的数据拷贝至内存地址中

  Marshal.Copy(arr, 0, ptr, arr.Length);

调用方法生成图像

HalconDotNet.HImage hImage = new HalconDotNet.HImage();
hImage.GenImage1("real", w, h, ptr);

完整代码

这个代码是控制台应用程序,并且使用控制退格控制来实现进度显示

 private static void ProcessFile(string fileName, string imgPath)
        {
            int start = Environment.TickCount;
            string[] lines = File.ReadAllLines(fileName);
            int w = lines[0].Split(',').Length;
            int h = lines.Length;
            float[] arr = new float[w * h];
            if (ptr == IntPtr.Zero)
            {
                ptr = Marshal.AllocHGlobal(arr.Length * sizeof(float));
            }
            int a = Console.CursorLeft;
            int b = Console.CursorTop;
            for (int i = 0; i < lines.Length; i++)
            {
                Console.SetCursorPosition(a+1, b);
                Console.WriteLine("{0}%", (i * 1.0 / lines.Length * 100).ToString("00"));
                string[] strs = lines[i].Split(',');
                for (int j = 0; j < w; j++)
                {
                    arr[i * w + j] = (float)Convert.ToDouble(strs[j]);
                }
            }
            string[] sss = fileName.Split('\\');
            string ImageName = imgPath + "\\" + sss[sss.Length - 1].Split('.')[0] + ".tif";
            Marshal.Copy(arr, 0, ptr, arr.Length);
            HalconDotNet.HImage hImage = new HalconDotNet.HImage();
            hImage.GenImage1("real", w, h, ptr);
            hImage.WriteImage("tiff", 0, ImageName);
            hImage.Dispose();

            Console.ForegroundColor = ConsoleColor.Green;
            int EndTick = Environment.TickCount;
            Console.WriteLine($"转换完成生成文件:{ImageName},耗时:{EndTick-start}ms");
        }

效果展示

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值