摘要
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");
}
效果展示