Exemple #1
0
        public static List <Vector3> Readlas(string lazfile)
        {
            // int classification = 0;
            var lazReader  = new laszip_dll();
            var compressed = true;

            lazReader.laszip_open_reader(lazfile, ref compressed);
            var numberOfPoints = lazReader.header.number_of_point_records;
            var coordArray     = new double[3];

            var points = new List <Vector3>();

            // Loop through number of points indicated
            for (int pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                var point = new Vector3();
                // Read the point
                lazReader.laszip_read_point();

                // Get precision coordinates
                lazReader.laszip_get_coordinates(coordArray);
                point.X = (float)coordArray[0];
                point.Y = (float)coordArray[1];
                point.Z = (float)coordArray[2];
                // point.W = lazReader.point.classification;

                points.Add(point);
                // Get classification value
            }

            lazReader.laszip_close_reader();
            return(points);
        }
Exemple #2
0
        private static IEnumerable <Points> ReadPoints(laszip_dll reader, int numberOfPointsPerChunk)
        {
            var n = reader.header.number_of_point_records;
            var numberOfChunks = n / numberOfPointsPerChunk;

            for (var j = 0; j < n; j += numberOfPointsPerChunk)
            {
                if (j + numberOfPointsPerChunk > n)
                {
                    numberOfPointsPerChunk = (int)(n - j);
                }
                //Console.WriteLine($"j: {j}, numberOfPointsPerChunk: {numberOfPointsPerChunk}, n: {n}");
                var p  = new double[3];
                var ps = new V3d[numberOfPointsPerChunk];
                var cs = new C4b[numberOfPointsPerChunk];
                var ts = new byte[numberOfPointsPerChunk];
                for (var i = 0; i < numberOfPointsPerChunk; i++)
                {
                    reader.laszip_read_point();

                    reader.laszip_get_coordinates(p);
                    ps[i] = new V3d(p);
                    cs[i] = new C4b(reader.point.rgb[0] >> 8, reader.point.rgb[1] >> 8, reader.point.rgb[2] >> 8);
                    ts[i] = reader.point.classification;
                }
                yield return(new Points(ps, cs, ts));
            }

            reader.laszip_close_reader();
        }
Exemple #3
0
        static void Main(string[] args)
        {
            long points = 0;

            foreach (var file in new System.IO.DirectoryInfo(Environment.CurrentDirectory).GetFiles())
            {
                var lazReader  = new laszip_dll();
                var compressed = true;
                var filePath   = args.Length > 0 ? args[0] : "SloveniaLidarRGB0.laz"; //@"C:\Users\jakak\Desktop\nrg-sem-Potree\pointclouds\Normals\data\r\00000\r00000.laz";
                filePath = file.FullName;

                lazReader.laszip_open_reader(filePath, ref compressed);
                var numberOfPoints = lazReader.header.number_of_point_records;
                var coordArray     = new double[3];
                points += numberOfPoints;
                Console.WriteLine("[{0:hh:mm:ss}] Reading LAZ... {1} points starting at {2}", DateTime.Now, numberOfPoints, lazReader.header.offset_to_point_data);

                for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
                {
                    lazReader.laszip_read_point();
                    lazReader.laszip_get_coordinates(coordArray);
                    var point  = lazReader.laszip_get_point_pointer();
                    var colors = point.rgb;
                    Console.WriteLine(String.Format("X {0} Y {1} Z {2} R {3:X} G {4:X} B {5:X}", point.X, point.Y, point.Z, colors[0], colors[1], colors[2]));

                    if (pointIndex % 20 == 0 && Console.ReadKey().Key == ConsoleKey.Q)
                    {
                        break;
                    }
                }
                Console.WriteLine("[DONE] ");
            }
            Console.WriteLine("Total: " + points);
            Console.Read();
        }
Exemple #4
0
        /// <summary>
        /// Returns info for given dataset.
        /// </summary>
        public static Info ReadInfo(Stream stream)
        {
            var reader     = new laszip_dll();
            var compressed = false;

            reader.laszip_open_reader(stream, ref compressed);
            return(ReadInfo(reader));
        }
Exemple #5
0
        /// <summary>
        /// Returns info for given dataset.
        /// </summary>
        public static Info ReadInfo(string filename)
        {
            var reader     = new laszip_dll();
            var compressed = false;

            reader.laszip_open_reader(filename, ref compressed);
            return(ReadInfo(reader));
        }
Exemple #6
0
        /// <summary>
        /// Reads point data from file and returns chunks of given size.
        /// </summary>
        public static IEnumerable <Points> ReadPoints(string filename, int numberOfPointsPerChunk, bool verbose)
        {
            var reader       = new laszip_dll();
            var isCompressed = false;

            reader.laszip_open_reader(filename, ref isCompressed);
            return(ReadPoints(reader, numberOfPointsPerChunk, verbose));
        }
Exemple #7
0
        /// <summary>
        /// Reads point data in chunks of given number of points.
        /// </summary>
        public static IEnumerable <Points> ReadPoints(Stream stream, int numberOfPointsPerChunk)
        {
            var reader       = new laszip_dll();
            var isCompressed = false;

            reader.laszip_open_reader(stream, ref isCompressed);
            return(ReadPoints(reader, numberOfPointsPerChunk));
        }
    // Read the file and move the point cloud to the center, and scale it down accordingly
    // Edges: length of the edges of the bounding box, use the longest one to scale the point cloud accordingly
    // Gravity: gravity of the point cloud to move the point cloud to the center
    List <point> ReadFile()
    {
        List <point> vecList = new List <point>();

        string path       = Application.persistentDataPath + filename;
        var    lazReader  = new laszip_dll();
        var    compressed = true;

        lazReader.laszip_open_reader(path, ref compressed);

        uint  num  = lazReader.header.number_of_point_records;
        float minX = (float)lazReader.header.min_x;
        float minY = (float)lazReader.header.min_y;
        float minZ = (float)lazReader.header.min_z;
        float maxX = (float)lazReader.header.max_x;
        float maxY = (float)lazReader.header.max_y;
        float maxZ = (float)lazReader.header.max_z;

        L = (int)(Mathf.Log(num / 8000) / Mathf.Log(Mathf.Pow(2, n))) + 1;

        var coord = new double[3];

        for (int pointIndex = 0; pointIndex < num; pointIndex++)
        {
            point node = new point();

            lazReader.laszip_read_point();

            lazReader.laszip_get_coordinates(coord);
            Vector3 xyz = new Vector3((float)coord[0], (float)coord[2], (float)coord[1]);

            Color colour = new Color32((byte)(lazReader.point.rgb[0] / 256), (byte)(lazReader.point.rgb[1] / 256), (byte)(lazReader.point.rgb[2] / 256), (byte)(lazReader.point.rgb[3] / 256));

            float U   = UnityEngine.Random.Range(0.0f, 1.0f);
            float lod = Mathf.Log((Mathf.Pow(2, (n - 1) * (L + 1)) - 1) * U + 1) / (n - 1) * Mathf.Log(2);

            node.xyz   = xyz;
            node.color = colour;
            node.lod   = lod;
            vecList.Add(node);
        }

        Vector3 min = new Vector3(minX, minY, minZ);
        Vector3 max = new Vector3(maxX, maxY, maxZ);

        Edges = max - min;

        lazReader.laszip_close_reader();

        vecList = vecList.OrderBy(element => element.lod).ToList();
        Vector3 bounds = (min + max) / 2;

        Center = new Vector3(bounds.x, minZ, bounds.y);

        return(vecList);
    }
Exemple #9
0
        private void LoadLasFile(string FileName)
        {
            sw.Start();
            points = new List <Point3D>();
            var lasReader  = new laszip_dll();
            var compressed = true;

            lasReader.laszip_open_reader(FileName, ref compressed);
            var    numberOfPoints = lasReader.header.number_of_point_records;
            double xmid, ymid, zmid;

            ratio = Math.Max(Math.Max(lasReader.header.max_x - lasReader.header.min_x, lasReader.header.max_y - lasReader.header.min_y),
                             lasReader.header.max_z - lasReader.header.min_z) / 2;
            ratio = (int)ratio + 1;
            xmid  = (lasReader.header.max_x + lasReader.header.min_x) / 2;
            ymid  = (lasReader.header.max_y + lasReader.header.min_y) / 2;
            zmid  = (lasReader.header.max_z + lasReader.header.min_z) / 2;
            int    classification = 0;
            var    coordArray     = new double[3];
            double zmin           = (lasReader.header.min_z - zmid) / ratio;
            double zmax           = (lasReader.header.max_z - zmid) / ratio;

            for (int pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)//循环读取每个点
            {
                lasReader.laszip_read_point();
                if (pointIndex % 10 == 0)//减少绘制的点数
                {
                    double x, y, z;
                    //  得到每个点坐标值
                    lasReader.laszip_get_coordinates(coordArray);
                    x = (coordArray[0] - xmid) / ratio;
                    y = (coordArray[1] - ymid) / ratio;
                    z = (coordArray[2] - zmid) / ratio;
                    points.Add(new Point3D(x, y, z, zmin, zmax));
                    classification = lasReader.point.classification;
                }
            }
            //  关闭
            lasReader.laszip_close_reader();
            octree = new Octree(points);

            PaintBall();
            MouseX = MouseY = 0;
            scale  = 1;
            Render();
            glControl1.Invalidate();
            sw.Stop();
            MessageBox.Show("共读取" + points.Count + "个点\n" +
                            "打开该点云文件耗时" + sw.ElapsedMilliseconds + "ms\n");
            sw.Reset();
        }
Exemple #10
0
        void WritePointcloud()
        {
            Console.WriteLine("[{0:hh:mm:ss}] Generating water...", DateTime.Now);
            List <XYZ> newPoints = new List <XYZ>();

            foreach (var polygon in polygons)
            {
                var grid = polygon.GetGrid(1.0, x * 1000, y * 1000, (x + 1) * 1000, (y + 1) * 1000);
                newPoints.AddRange(grid);
            }

            Console.WriteLine("[{0:hh:mm:ss}] Writing LAZ...", DateTime.Now);
            lazReader.laszip_seek_point(0L);//read from the beginning again

            lazWriter        = new laszip_dll();
            lazWriter.header = lazReader.header;

            lazWriter.header.number_of_point_records += (uint)newPoints.Count;
            lazWriter.laszip_open_writer(destPath, true);

            var coordArray = new double[3];

            for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                lazReader.laszip_read_point();
                lazReader.laszip_get_coordinates(coordArray);
                lazWriter.point = lazReader.point;
                //if (lazWriter.point.classification > 9) System.Diagnostics.Debugger.Break();
                if (pointcloud.ContainsKey(pointIndex))
                {
                    lazWriter.point.classification = WATER_CLASSIFICATION;
                }

                lazWriter.laszip_write_point();
            }

            Console.WriteLine("[{0:hh:mm:ss}] Adding water...", DateTime.Now);
            foreach (var gridPoint in newPoints)
            {
                lazWriter.point.classification  = 9;
                lazWriter.point.point_source_ID = 1234;
                coordArray[0] = gridPoint.x;
                coordArray[1] = gridPoint.y;
                coordArray[2] = gridPoint.z;
                lazWriter.laszip_set_coordinates(coordArray);
                lazWriter.laszip_write_point();
            }
            lazReader.laszip_close_reader();
            lazWriter.laszip_close_writer();
        }
Exemple #11
0
        private static Info ReadInfo(laszip_dll reader)
        {
            var count = reader.header.number_of_point_records;

            var bounds = new Box3d(
                new V3d(
                    reader.header.min_x,
                    reader.header.min_y,
                    reader.header.min_z),
                new V3d(
                    reader.header.max_x,
                    reader.header.max_y,
                    reader.header.max_z)
                );

            reader.laszip_close_reader();

            return(new Info(count, bounds));
        }
Exemple #12
0
        private static Info ReadInfo(laszip_dll reader)
        {
            var count = reader.header.number_of_point_records;

            var bounds = new Box3d(
                new V3d(
                    reader.header.x_scale_factor * reader.header.min_x + reader.header.x_offset,
                    reader.header.y_scale_factor * reader.header.min_y + reader.header.y_offset,
                    reader.header.z_scale_factor * reader.header.min_z + reader.header.z_offset),
                new V3d(
                    reader.header.x_scale_factor * reader.header.max_x + reader.header.x_offset,
                    reader.header.y_scale_factor * reader.header.max_y + reader.header.y_offset,
                    reader.header.z_scale_factor * reader.header.max_z + reader.header.z_offset)
                );

            reader.laszip_close_reader();

            return(new Info(count, bounds));
        }
Exemple #13
0
        static void ReadLaz()
        {
            var lazReader  = new laszip_dll();
            var compressed = true;

            lazReader.laszip_open_reader(FileName, ref compressed);
            var numberOfPoints = lazReader.header.number_of_point_records;

            // Check some header values
            Debug.WriteLine(lazReader.header.min_x);
            Debug.WriteLine(lazReader.header.min_y);
            Debug.WriteLine(lazReader.header.min_z);
            Debug.WriteLine(lazReader.header.max_x);
            Debug.WriteLine(lazReader.header.max_y);
            Debug.WriteLine(lazReader.header.max_z);

            int classification = 0;
            var point          = new Point3D();
            var coordArray     = new double[3];

            // Loop through number of points indicated
            for (int pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                // Read the point
                lazReader.laszip_read_point();

                // Get precision coordinates
                lazReader.laszip_get_coordinates(coordArray);
                point.X = coordArray[0];
                point.Y = coordArray[1];
                point.Z = coordArray[2];

                // Get classification value
                classification = lazReader.point.classification;
            }

            // Close the reader
            lazReader.laszip_close_reader();
        }
Exemple #14
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string filename = string.Empty;

            DA.GetData <string>(0, ref filename);

            Brep boundary = new Brep();

            DA.GetData <Brep>(1, ref boundary);

            bool        filter = (boundary.IsValid);
            BoundingBox bbox   = boundary.GetBoundingBox(true);

            if (filter)
            {
                AddPreviewItem(bbox);
            }

            List <string> info = new List <string>();

            var lazReader  = new laszip_dll();
            var compressed = true;

            lazReader.laszip_open_reader(filename, ref compressed);
            var numberOfPoints     = lazReader.header.number_of_point_records;
            List <laszip_vlr> vlrs = lazReader.header.vlrs;

            info.Add("Points: " + lazReader.header.number_of_point_records.ToString("N0"));
            info.Add("Returns: " + lazReader.header.number_of_points_by_return.Length);
            info.Add("File source ID: " + lazReader.header.file_source_ID);
            info.Add("Created on: " + lazReader.header.file_creation_day + " day of " + lazReader.header.file_creation_year);
            info.Add("Created with: " + Encoding.Default.GetString(lazReader.header.generating_software));

            ///Try to fetch SRS of point cloud
            string pcSRS = "Data does not have associated spatial reference system (SRS).";

            foreach (var vlr in vlrs)
            {
                string description = Encoding.Default.GetString(vlr.description);
                if (description.Contains("SRS") || description.Contains("WKT"))
                {
                    pcSRS = Encoding.Default.GetString(vlr.data);
                }
            }

            Point3d     min    = new Point3d(lazReader.header.min_x, lazReader.header.min_y, lazReader.header.min_z);
            Point3d     max    = new Point3d(lazReader.header.max_x, lazReader.header.max_y, lazReader.header.max_z);
            BoundingBox maxBox = new BoundingBox(min, max);

            AddPreviewItem(maxBox);

            Message = numberOfPoints.ToString("N0") + " points";

            PointCloud pointCloud             = new PointCloud();
            GH_Structure <GH_Point>  ghPC     = new GH_Structure <GH_Point>();
            GH_Structure <GH_Colour> ghColors = new GH_Structure <GH_Colour>();

            var coordArray = new double[3];

            for (int pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                ///Read the point
                lazReader.laszip_read_point();

                ///Get precision coordinates
                lazReader.laszip_get_coordinates(coordArray);
                Point3d pt = new Point3d(coordArray[0], coordArray[1], coordArray[2]);

                ///Get classification value for sorting into branches
                int     classification = lazReader.point.classification;
                GH_Path path           = new GH_Path(classification);

                GH_Colour col = new GH_Colour(Color.FromArgb(lazReader.point.rgb[0], lazReader.point.rgb[1], lazReader.point.rgb[2]));

                if (!filter)
                {
                    ghPC.Append(new GH_Point(pt), new GH_Path(classification));
                    ghColors.Append(col, new GH_Path(classification));
                }

                else
                {
                    if (bbox.Contains(pt))
                    {
                        ghPC.Append(new GH_Point(pt), new GH_Path(classification));
                        ghColors.Append(col, new GH_Path(classification));
                    }
                }
            }
            lazReader.laszip_close_reader();

            DA.SetDataList(0, info);
            DA.SetDataTree(1, ghPC);
            DA.SetDataTree(2, ghColors);
            DA.SetData(3, pcSRS);
        }
        //reads LAZ, builds KD tree, reads LAZ again and sets color & normal and writes
        private void EnrichLazWithRGBSAndNormals(string chunk)
        {
            var lazReader  = new laszip_dll();
            var compressed = true;
            var filePath   = LidarFilesSavePath + tempfile2name(chunk);

            lazReader.laszip_open_reader(filePath, ref compressed);
            var numberOfPoints = lazReader.header.number_of_point_records;
            var coordArray     = new double[3];
            var kdTree         = new KDTree(3);

            if (IncludeNormals)
            {
                Console.Write("[{0:hh:mm:ss}] Reading LAZ and building KD tree...", DateTime.Now);
                for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
                {
                    lazReader.laszip_read_point();
                    lazReader.laszip_get_coordinates(coordArray);

                    kdTree.Add(coordArray);
                }
                Console.WriteLine("[DONE] ");
            }
            var img = GetOrthophotoImg();

            Console.Write("[{0:hh:mm:ss}] Reading and writing LAZ...", DateTime.Now);
            lazReader.laszip_seek_point(0L);//read from the beginning again
            lazReader.laszip_open_reader(filePath, ref compressed);

            var lazWriter = new laszip_dll();

            lazWriter.header = lazReader.header;
            lazWriter.laszip_open_writer(LidarFilesSavePath + current + ".laz", true);

            for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                lazReader.laszip_read_point();
                lazReader.laszip_get_coordinates(coordArray);
                lazWriter.point = lazReader.point;

                int[] pxCoordinates = FindClosestPxCoordinates(coordArray[0], coordArray[1]);
                int   i             = (pxCoordinates[0] - _bottomLeftX) * 2;
                int   j             = img.Height - 1 - ((pxCoordinates[1] - _bottomLeftY) * 2); //j index of image goes from top to bottom

                Color color = img.GetPixel(i, j);                                               //binary int value
                lazReader.point.rgb = new[] {
                    (ushort)(color.R << 8),
                    (ushort)(color.G << 8),
                    (ushort)(color.B << 8),
                    (ushort)0
                };

                if (IncludeNormals)
                {
                    var kNeighbours = kdTree.ApproximateNearest(coordArray, 20, 1000);
                    var normal      = GetNormal(coordArray, kNeighbours);

                    var xt = (float)normal[0];//xt in LAS is float
                    var yt = (float)normal[1];
                    var zt = (float)normal[2];

                    var xtBytes = BitConverter.GetBytes(xt);
                    var ytBytes = BitConverter.GetBytes(yt);
                    var ztBytes = BitConverter.GetBytes(zt);

                    var waveformPacket = lazWriter.point.wave_packet;
                    waveformPacket[17] = xtBytes[0];
                    waveformPacket[18] = xtBytes[1];
                    waveformPacket[19] = xtBytes[2];
                    waveformPacket[20] = xtBytes[3];

                    waveformPacket[21] = ytBytes[0];
                    waveformPacket[22] = ytBytes[1];
                    waveformPacket[23] = ytBytes[2];
                    waveformPacket[24] = ytBytes[3];

                    waveformPacket[25] = ztBytes[0];
                    waveformPacket[26] = ztBytes[1];
                    waveformPacket[27] = ztBytes[2];
                    waveformPacket[28] = ztBytes[3];
                }
                lazWriter.laszip_write_point();
            }
            lazReader.laszip_close_reader();
            lazWriter.laszip_close_writer();

            Console.WriteLine("[DONE]");
        }//end readwrite function
Exemple #16
0
        public void Start()
        {
            var lazReader  = new laszip_dll();
            var compressed = true;
            var filePath   = ResourceDirectoryPath + "/5-" + x + "-" + y + ".laz";


            //var kdTree = new KDTree(3);
            Bitmap img = null;

            for (int i = 0; i < 4; i++)
            {
                try
                {
                    img = GetOrthophotoImg();
                    break;
                }
                catch (Exception e) {
                    Console.WriteLine("[{0:hh:mm:ss}] Image download failed...", DateTime.Now);
                    Console.WriteLine("[{0:hh:mm:ss}] {1}", DateTime.Now, e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            }
            if (img == null)
            {
                throw new Exception();
            }

            lazReader.laszip_open_reader(filePath, ref compressed);
            var numberOfPoints = lazReader.header.number_of_point_records;

            Console.WriteLine("[{0:hh:mm:ss}] Reading and writing LAZ...", DateTime.Now);
            lazReader.laszip_seek_point(0L);//read from the beginning again
            lazReader.laszip_open_reader(filePath, ref compressed);

            var lazWriter = new laszip_dll();

            lazWriter.header = lazReader.header;
            lazWriter.laszip_open_writer(ResourceDirectoryPath + "/6-" + x + "-" + y + ".laz", true);

            for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                var coordArray = new double[3];
                lazReader.laszip_read_point();
                lazReader.laszip_get_coordinates(coordArray);
                lazWriter.point = lazReader.point;

                int[] pxCoordinates = FindClosestPxCoordinates(coordArray[0], coordArray[1]);
                int   i             = (pxCoordinates[0] - _bottomLeftX) * 2;
                int   j             = img.Height - 1 - ((pxCoordinates[1] - _bottomLeftY) * 2);//j index of image goes from top to bottom

                i = Math.Max(Math.Min(i, img.Width - 1), 0);
                j = Math.Max(Math.Min(j, img.Height - 1), 0);

                Color color = img.GetPixel(i, j); //binary int value
                lazReader.point.rgb = new[] {
                    (ushort)(color.R << 8),
                    (ushort)(color.G << 8),
                    (ushort)(color.B << 8),
                    (ushort)0
                };
                lazWriter.laszip_write_point();
            }
            lazReader.laszip_close_reader();
            lazWriter.laszip_close_writer();
        }
Exemple #17
0
        //reads LAZ, builds KD tree, reads LAZ again and sets color & normal and writes
        private void ReadWriteLaz()
        {
            var lazReader  = new laszip_dll();
            var compressed = true;
            var filePath   = ResourceDirectoryPath + id + "-laz13.laz";

            lazReader.laszip_open_reader(filePath, ref compressed);
            var numberOfPoints = lazReader.header.number_of_point_records;
            //var kdTree = new KDTree(3);
            var kdTree = new KdTree <double, object>(3, new KdTree.Math.DoubleMath(), AddDuplicateBehavior.Update);

            if (IncludeNormals)
            {
                Console.WriteLine("[#{0} {1:hh:mm:ss}] Reading LAZ and building KD tree...", id, DateTime.Now);
                for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
                {
                    var coordArray = new double[3];
                    lazReader.laszip_read_point();
                    lazReader.laszip_get_coordinates(coordArray);
                    //Thread.Sleep(1);
                    //kdTree.Add(coordArray);
                    kdTree.Add(coordArray, null);
                    //Console.WriteLine("Point {0} {1} {2}", coordArray[0], coordArray[1], coordArray[2]);
                }
                //Console.WriteLine("[DONE] ");

                Console.WriteLine("[#{0} {1:hh:mm:ss}] Balancing KD tree...", id, DateTime.Now);
                kdTree.Balance();
                //Console.WriteLine("[DONE] ");
            }

            var img = GetOrthophotoImg();

            Console.WriteLine("[#{0} {1:hh:mm:ss}] Reading and writing LAZ...", id, DateTime.Now);
            lazReader.laszip_seek_point(0L);//read from the beginning again
            lazReader.laszip_open_reader(filePath, ref compressed);

            var lazWriter = new laszip_dll();

            lazWriter.header = lazReader.header;
            lazWriter.laszip_open_writer(ResourceDirectoryPath + "SloveniaLidarRGB" + id + ".laz", true);

            stw = new Stopwatch();
            stw.Restart();
            for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                if (pointIndex % 100000 == 0)
                {
                    double elaspedHours   = stw.Elapsed.TotalHours;
                    double finishedShare  = (double)pointIndex / numberOfPoints;
                    double totalHours     = elaspedHours / finishedShare;
                    double remainingHours = totalHours - elaspedHours;
                    Console.WriteLine(
                        "[#{0} {1:hh:mm:ss}] Finished " + (pointIndex / 1000) + "k / " + (numberOfPoints / 1000) + "k | " + Math.Round(remainingHours, 2) + " hours remaining",
                        id, DateTime.Now);
                }

                var coordArray = new double[3];
                lazReader.laszip_read_point();
                lazReader.laszip_get_coordinates(coordArray);
                lazWriter.point = lazReader.point;

                int[] pxCoordinates = FindClosestPxCoordinates(coordArray[0], coordArray[1]);
                int   i             = (pxCoordinates[0] - _bottomLeftX) * 2;
                int   j             = img.Height - 1 - ((pxCoordinates[1] - _bottomLeftY) * 2); //j index of image goes from top to bottom

                Color color = img.GetPixel(i, j);                                               //binary int value
                lazReader.point.rgb = new[] {
                    (ushort)(color.R << 8),
                    (ushort)(color.G << 8),
                    (ushort)(color.B << 8),
                    (ushort)0
                };

                if (IncludeNormals)
                {
                    //var kNeighbours = kdTree.ApproximateNearest(coordArray, 20, 1000);
                    var kNeighbours = kdTree.GetNearestNeighbours(coordArray, 20);
                    var collection  = new KDTreeNodeCollection <KDTreeNode>(20);
                    for (int k = 0; k < 20; k++)
                    {
                        collection.Add(new KDTreeNode {
                            Position = kNeighbours[k].Point
                        }, 0);
                    }
                    var normal = GetNormal(coordArray, collection);

                    lazReader.point.rgb[0] |= (byte)((normal[0] + 1.0) * 128.0);
                    lazReader.point.rgb[1] |= (byte)((normal[1] + 1.0) * 128.0);
                    lazReader.point.rgb[2] |= (byte)((normal[2] + 1.0) * 128.0);

                    /*var xt = (float)normal[0];//xt in LAS is float
                     * var yt = (float)normal[1];
                     * var zt = (float)normal[2];
                     *
                     * var xtBytes = BitConverter.GetBytes(xt);
                     * var ytBytes = BitConverter.GetBytes(yt);
                     * var ztBytes = BitConverter.GetBytes(zt);
                     *
                     * var waveformPacket = lazWriter.point.wave_packet;
                     * waveformPacket[17] = xtBytes[0];
                     * waveformPacket[18] = xtBytes[1];
                     * waveformPacket[19] = xtBytes[2];
                     * waveformPacket[20] = xtBytes[3];
                     *
                     * waveformPacket[21] = ytBytes[0];
                     * waveformPacket[22] = ytBytes[1];
                     * waveformPacket[23] = ytBytes[2];
                     * waveformPacket[24] = ytBytes[3];
                     *
                     * waveformPacket[25] = ztBytes[0];
                     * waveformPacket[26] = ztBytes[1];
                     * waveformPacket[27] = ztBytes[2];
                     * waveformPacket[28] = ztBytes[3];*/
                }
                lazWriter.laszip_write_point();
            }
            lazReader.laszip_close_reader();
            lazWriter.laszip_close_writer();

            //Console.WriteLine("[DONE]");
        }//end readwrite function
Exemple #18
0
        private static void WriteLaz()
        {
            // --- Write Example
            var point  = new Point3D();
            var points = new List <Point3D>();

            point.X = 1000.0;
            point.Y = 2000.0;
            point.Z = 100.0;
            points.Add(point);

            point.X = 5000.0;
            point.Y = 6000.0;
            point.Z = 200.0;
            points.Add(point);

            var lazWriter = new laszip_dll();
            var err       = lazWriter.laszip_clean();

            if (err == 0)
            {
                // Number of point records needs to be set
                lazWriter.header.number_of_point_records = (uint)points.Count;

                // Header Min/Max needs to be set to extents of points
                lazWriter.header.min_x = points[0].X;                 // LL Point
                lazWriter.header.min_y = points[0].Y;
                lazWriter.header.min_z = points[0].Z;
                lazWriter.header.max_x = points[1].X;                 // UR Point
                lazWriter.header.max_y = points[1].Y;
                lazWriter.header.max_z = points[1].Z;

                // Open the writer and test for errors
                err = lazWriter.laszip_open_writer(FileName, true);
                if (err == 0)
                {
                    double[] coordArray = new double[3];
                    foreach (var p in points)
                    {
                        coordArray[0] = p.X;
                        coordArray[1] = p.Y;
                        coordArray[2] = p.Z;

                        // Set the coordinates in the lazWriter object
                        lazWriter.laszip_set_coordinates(coordArray);

                        // Set the classification to ground
                        lazWriter.point.classification = 2;

                        // Write the point to the file
                        err = lazWriter.laszip_write_point();
                        if (err != 0)
                        {
                            break;
                        }
                    }

                    // Close the writer to release the file (OS lock)
                    err       = lazWriter.laszip_close_writer();
                    lazWriter = null;
                }
            }

            if (err != 0)
            {
                // Show last error that occurred
                Debug.WriteLine(lazWriter.laszip_get_error());
            }
            // --- Upon completion, file should be 389 bytes
        }
Exemple #19
0
        private static IEnumerable <Points> ReadPoints(laszip_dll reader, int numberOfPointsPerChunk, bool verbose)
        {
            var n = reader.header.number_of_point_records;
            //var numberOfChunks = n / numberOfPointsPerChunk;

            var format        = reader.header.point_data_format;
            var hasGpsTime    = format == 1 || format == 3 || format == 4 || format == 5;
            var hasColor      = format == 2 || format == 3 || format == 5;
            var hasWavePacket = format == 4 || format == 5;

            for (var j = 0; j < n; j += numberOfPointsPerChunk)
            {
                if (j + numberOfPointsPerChunk > n)
                {
                    numberOfPointsPerChunk = (int)(n - j);
                }
                if (verbose)
                {
                    Console.WriteLine($"j: {j}, numberOfPointsPerChunk: {numberOfPointsPerChunk}, n: {n}");
                }

                // POINT10
                var p                       = new double[3];
                var ps                      = new V3d[numberOfPointsPerChunk];
                var intensities             = new ushort[numberOfPointsPerChunk];
                var returnNumbers           = new byte[numberOfPointsPerChunk];
                var numberOfReturnsOfPulses = new byte[numberOfPointsPerChunk];
                var scanDirectionFlags      = new BitArray(numberOfPointsPerChunk);
                var edgeOfFlightLines       = new BitArray(numberOfPointsPerChunk);
                var classifications         = new byte[numberOfPointsPerChunk];
                var scanAngleRanks          = new byte[numberOfPointsPerChunk];
                var userDatas               = new byte[numberOfPointsPerChunk];
                var pointSourceIds          = new ushort[numberOfPointsPerChunk];

                // GPSTIME10
                var gpsTimes = hasGpsTime ? new double[numberOfPointsPerChunk] : null;

                // RGB12
                var  colorsRaw   = hasColor ? new C3us[numberOfPointsPerChunk] : null;
                bool colorIs8Bit = true;

                // WAVEPACKET13
                var wavePacketDescriptorIndices  = hasWavePacket ? new byte[numberOfPointsPerChunk] : null;
                var bytesOffsetToWaveformDatas   = hasWavePacket ? new ulong[numberOfPointsPerChunk] : null;
                var waveformPacketSizesInBytes   = hasWavePacket ? new uint[numberOfPointsPerChunk] : null;
                var returnPointWaveformLocations = hasWavePacket ? new float[numberOfPointsPerChunk] : null;
                var xts = hasWavePacket ? new float[numberOfPointsPerChunk] : null;
                var yts = hasWavePacket ? new float[numberOfPointsPerChunk] : null;
                var zts = hasWavePacket ? new float[numberOfPointsPerChunk] : null;

                for (var i = 0; i < numberOfPointsPerChunk; i++)
                {
                    reader.laszip_read_point();

                    reader.laszip_get_coordinates(p);
                    ps[i]                      = new V3d(p);
                    intensities[i]             = reader.point.intensity;
                    returnNumbers[i]           = reader.point.return_number;
                    numberOfReturnsOfPulses[i] = reader.point.number_of_returns_of_given_pulse;
                    scanDirectionFlags[i]      = reader.point.scan_direction_flag != 0;
                    edgeOfFlightLines[i]       = reader.point.edge_of_flight_line != 0;
                    classifications[i]         = reader.point.classification;
                    scanAngleRanks[i]          = (byte)reader.point.scan_angle_rank;
                    userDatas[i]               = reader.point.user_data;
                    pointSourceIds[i]          = reader.point.point_source_ID;

                    if (hasGpsTime)
                    {
                        gpsTimes[i] = reader.point.gps_time;
                    }

                    if (hasColor)
                    {
                        var c = new C3us(reader.point.rgb[0], reader.point.rgb[1], reader.point.rgb[2]);
                        colorsRaw[i] = c;
                        if (colorIs8Bit && (c.R > 255 || c.G > 255 || c.B > 255))
                        {
                            colorIs8Bit = false;
                        }
                    }

                    if (hasWavePacket)
                    {
                        var buffer = reader.point.wave_packet;
                        wavePacketDescriptorIndices[i]  = buffer[0];
                        bytesOffsetToWaveformDatas[i]   = BitConverter.ToUInt64(buffer, 1);
                        waveformPacketSizesInBytes[i]   = BitConverter.ToUInt32(buffer, 9);
                        returnPointWaveformLocations[i] = BitConverter.ToSingle(buffer, 13);
                        xts[i] = BitConverter.ToSingle(buffer, 17);
                        yts[i] = BitConverter.ToSingle(buffer, 21);
                        zts[i] = BitConverter.ToSingle(buffer, 25);
                    }
                }

                var colors = (colorsRaw, colorIs8Bit) switch
                {
                    (null, _) => null,
                    (not null, true) => colorsRaw.Map(c => new C3b(c.R, c.G, c.B)),
                    (not null, false) => colorsRaw.Map(c => new C3b(c.R >> 8, c.G >> 8, c.B >> 8))
                };

                //if (verbose)
                //{
                //    if (ps?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] positions");
                //    if (intensities?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] intensities");
                //    if (returnNumbers?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] returnNumbers");
                //    if (numberOfReturnsOfPulses?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] numberOfReturnsOfPulses");
                //    if (classifications?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] classifications");
                //    if (scanAngleRanks?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] scanAngleRanks");
                //    if (userDatas?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] userDatas");
                //    if (pointSourceIds?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] pointSourceIds");
                //    if (gpsTimes?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] gpsTimes");
                //    if (colors?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] colors");
                //    if (wavePacketDescriptorIndices?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] wavePacketDescriptorIndices");
                //    if (bytesOffsetToWaveformDatas?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] bytesOffsetToWaveformDatas");
                //    if (waveformPacketSizesInBytes?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] waveformPacketSizesInBytes");
                //    if (returnPointWaveformLocations?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] returnPointWaveformLocations");
                //    if (xts?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] xts");
                //    if (yts?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] yts");
                //    if (zts?.Distinct()?.Count() > 1) Report.WarnNoPrefix("[Laszip.ReadPoints] zts");
                //}

                yield return(new Points
                {
                    Positions = ps,
                    Intensities = intensities,
                    ReturnNumbers = returnNumbers,
                    NumberOfReturnsOfPulses = numberOfReturnsOfPulses,
                    ScanDirectionFlags = scanDirectionFlags,
                    EdgeOfFlightLines = edgeOfFlightLines,
                    Classifications = classifications,
                    ScanAngleRanks = scanAngleRanks,
                    UserDatas = userDatas,
                    PointSourceIds = pointSourceIds,

                    GpsTimes = gpsTimes,

                    Colors = colors,

                    WavePacketDescriptorIndices = wavePacketDescriptorIndices,
                    BytesOffsetToWaveformDatas = bytesOffsetToWaveformDatas,
                    WaveformPacketSizesInBytes = waveformPacketSizesInBytes,
                    ReturnPointWaveformLocations = returnPointWaveformLocations,
                    Xts = xts,
                    Yts = yts,
                    Zts = zts
                });
            }

            reader.laszip_close_reader();
        }
Exemple #20
0
        void LoadPointcloud()
        {
            Console.WriteLine("[{0:hh:mm:ss}] Reading LAZ...", DateTime.Now);
            pointcloud = new Dictionary <int, XYZ>();
            lazReader  = new laszip_dll();
            var compressed = true;

            lazReader.laszip_open_reader(sourcePath, ref compressed);
            numberOfPoints = lazReader.header.number_of_point_records;

            Console.WriteLine("[{0:hh:mm:ss}] Total: {1} mio points", DateTime.Now, Math.Round(numberOfPoints / 1000000.0, 2));

            /*foreach (var item in polygons)
             * {
             *  Console.WriteLine(GetGeogebraString(item.ringPoints.ToList()));
             * }*/

            for (var pointIndex = 0; pointIndex < numberOfPoints; pointIndex++)
            {
                if (pointIndex % 1000000 == 0 && pointIndex > 0)
                {
                    Console.WriteLine("[{0:hh:mm:ss}] {1} mio points processed", DateTime.Now, pointIndex / 1000000);
                }
                var coordArray = new double[3];
                lazReader.laszip_read_point();
                lazReader.laszip_get_coordinates(coordArray);
                XYZ point = new XYZ()
                {
                    x = coordArray[0], y = coordArray[1], z = coordArray[2]
                };
                foreach (var polygon in polygons)
                {
                    if (polygon.InPolygon(point) || polygon.DistanceFromCoast(point) < 5)
                    {
                        if (lazReader.point.classification == WATER_CLASSIFICATION)
                        {
                            polygon.points[pointIndex] = point;
                            pointcloud[pointIndex]     = point;
                        }
                        if (lazReader.point.classification == GROUND_CLASSIFICATION ||
                            lazReader.point.classification == WATER_CLASSIFICATION)
                        {
                            polygon.allPoints[pointIndex] = point;
                        }
                        break;
                    }
                }
            }

            /*
             * foreach (var item in polygons)
             * {
             *  Console.WriteLine(GetGeogebraString(Subsample(item.allPoints.Values.ToList(), 10)));
             * }*/

            foreach (var polygon in polygons.Where(p => p.allPoints.Count > 0))
            {
                //var treeData = polygon.allPoints.Values.Select(p => new double[] { p.x, p.y }).ToArray();
                //KDTree<double, XYZ> tree = new KDTree<double, XYZ>(2, treeData, polygon.allPoints.Values.ToArray(), L2Norm);
                polygon.AssignHeghts();

                /*double elevation;
                 * if (polygon.points.Count > 0) elevation = polygon.points.Select(p => p.Value.z).Average();
                 * else elevation = polygon.allPoints.Select(p => p.Value.z).Min();*/

                foreach (var point in polygon.allPoints)
                {
                    if (!pointcloud.ContainsKey(point.Key) /*&&
                                                            * polygon.IsOnWater(point.Value, 15)*/)
                    {
                        /*var nearestPoints = tree.NearestNeighbors(
                         *  new double[] { point.Value.x, point.Value.y }, 100);
                         * var z = nearestPoints.Min(p => p.Item2.z);
                         */
                        var nearest   = polygon.ringsTree.NearestNeighbors(new double[] { point.Value.x, point.Value.y }, 3);
                        var elevation = nearest.Select(p => p.Item2.z).Average();
                        if (point.Value.z < elevation + 2.0 &&
                            polygon.IsOnWater(point.Value, 15))
                        {
                            polygon.points[point.Key] = point.Value;
                            pointcloud[point.Key]     = point.Value;
                        }
                    }
                }
            }
            var ringPoints = polygons
                             .Where(p => p.allPoints.Count > 0)
                             .SelectMany(p => p.ringPoints);

            if (ringPoints.Count() > 0)
            {
                foreach (var polygon in polygons.Where(p => p.allPoints.Count == 0))
                {
                    polygon.AssignHeghts(ringPoints);
                }
            }
            else
            {
                //throw new Exception("No points to determine ring heights!");
                Console.WriteLine("No points to determine ring heights");
                System.IO.File.Copy(sourcePath, destPath);
                System.Environment.Exit(0);
            }
        }