private static HeightMap ParseGeoData(GeoTiff tiff, FileMetadata metadata) { HeightMap heightMap = new HeightMap(metadata.Width, metadata.Height); byte[] scanline = new byte[metadata.ScanlineSize]; ushort[] scanline16Bit = new ushort[metadata.ScanlineSize / 2]; Buffer.BlockCopy(scanline, 0, scanline16Bit, 0, scanline.Length); for (int y = 0; y < metadata.Height; y++) { tiff.TiffFile.ReadScanline(scanline, y); Buffer.BlockCopy(scanline, 0, scanline16Bit, 0, scanline.Length); double latitude = metadata.StartLat + (metadata.pixelSizeY * y); for (int x = 0; x < scanline16Bit.Length; x++) { double longitude = metadata.StartLon + (metadata.pixelSizeX * x); float heightValue = (float)scanline16Bit[x]; if (heightValue < 32768) { heightMap.Mininum = Math.Min(metadata.MininumAltitude, heightValue); heightMap.Maximum = Math.Max(metadata.MaximumAltitude, heightValue); } else { heightValue = NO_DATA_OUT; } heightMap.Coordinates.Add(new GeoPoint(latitude, longitude, heightValue, x, y)); } } return(heightMap); }
public HeightMap GetHeightMap(BoundingBox bbox, DEMDataSet dataSet) { // Locate which files are needed // Find files matching coords List <FileMetadata> bboxMetadata = GetCoveringFiles(bbox, dataSet); HeightMap heightMap = null; // get height map for each file at bbox foreach (FileMetadata metadata in bboxMetadata) { using (GeoTiff geoTiff = new GeoTiff(metadata.Filename)) { heightMap = this.ParseGeoDataInBBox(geoTiff, bbox, metadata); } } FileMetadata meta = bboxMetadata.First(); using (GeoTiff geoTiff = new GeoTiff(meta.Filename)) { heightMap = this.ParseGeoDataInBBox(geoTiff, bbox, meta); } return(heightMap); }
public CustomMapGeotiff(GeoTiff geoTiff) : base(geoTiff.MapName, new GeoCoord(geoTiff.TopLeftLng, geoTiff.TopLeftLat)) { m_geoTiff = geoTiff; m_enabled = true; setImage(); // actually reads geotiff and sets image and location (loc) }
private static void GeoTiffTests(IGeoTiffService geoTiffService, string tiffPath) { FileMetadata metaData = geoTiffService.ParseMetadata(tiffPath); float elevation; using (GeoTiff tiff = new GeoTiff(tiffPath)) { elevation = tiff.ParseGeoDataAtPoint(metaData, 122, 122); } }
static void Main(string[] args) { // OBJ Testing var objMetadataOutput = Path.Combine(Path.GetDirectoryName(objPath), "objSample.json"); if (File.Exists(objMetadataOutput)) { File.Delete(objMetadataOutput); } var objBinaryOutput = Path.Combine(Path.GetDirectoryName(objPath), "objSample.dat"); if (File.Exists(objBinaryOutput)) { File.Delete(objBinaryOutput); } var objBitmapOutput = Path.Combine(Path.GetDirectoryName(objPath), "objSample.bmp"); if (File.Exists(objBitmapOutput)) { File.Delete(objBitmapOutput); } var objConverter = new GeoObj(); objConverter.ConvertToHeightMap(objPath, objBinaryOutput, objMetadataOutput, objBitmapOutput); // Save metadata var outputManifestPath = Path.Combine(Path.GetDirectoryName(tiffPath), "tiffSample4.json"); if (File.Exists(outputManifestPath)) { File.Delete(outputManifestPath); } // Save image var outputPath = Path.Combine(Path.GetDirectoryName(tiffPath), "tiffSample4.dat"); if (File.Exists(outputPath)) { File.Delete(outputPath); } var bitmapPath = Path.Combine(Path.GetDirectoryName(tiffPath), "tiffSample4.bmp"); if (File.Exists(bitmapPath)) { File.Delete(bitmapPath); } using (GeoTiff tiffConverter = new GeoTiff()) { tiffConverter.ConvertToHeightMap(tiffPath, outputPath, outputManifestPath, bitmapPath); } }
// Rough implementation, support for zipped tiff's private IEnumerable <string> ConvertFiles(string filePath, string sourceName) { string workingDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); Directory.CreateDirectory(workingDirectory); // If ZIP, extract first if (string.Equals(Path.GetExtension(sourceName), ".zip", StringComparison.OrdinalIgnoreCase)) { Trace.TraceInformation("Found zip file, decompressing."); ZipFile.ExtractToDirectory(filePath, workingDirectory); var files = Directory.GetFiles(workingDirectory); // Lets see if we have a tiff file for now var tiff = files.Where(f => string.Equals(Path.GetExtension(f), ".tif", StringComparison.OrdinalIgnoreCase)).FirstOrDefault(); if (!string.IsNullOrEmpty(tiff)) { Trace.TraceInformation("Found tiff, converting."); var GeoTiff = new GeoTiff(); var outputRoot = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString("N")); var outputBinary = outputRoot + ".dat"; var outputMetadata = outputRoot + ".json"; var outputThumbnail = outputRoot + ".jpg"; GeoTiff.ConvertToHeightMap(tiff, outputBinary, outputMetadata, outputThumbnail); try { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } Directory.Delete(workingDirectory, true); } catch (Exception ex) { Trace.TraceWarning("Failed to cleanup working files. {0}", ex.ToString()); } return(new List <string> { outputBinary, outputMetadata, outputThumbnail }); } } return(null); }
public static HeightMap GetHeightMap(string fileName, FileMetadata metadata) { fileName = Path.GetFullPath(fileName); string fileTitle = Path.GetFileNameWithoutExtension(fileName); HeightMap heightMap = null; using (GeoTiff tiff = new GeoTiff(fileName)) { heightMap = ParseGeoData(tiff, metadata); } return(heightMap); }
public HeightMap ParseGeoDataInBBox(GeoTiff tiff, BoundingBox bbox, FileMetadata metadata) { HeightMap heightMap = new HeightMap(metadata.Width, metadata.Height); byte[] scanline = new byte[metadata.ScanlineSize]; ushort[] scanline16Bit = new ushort[metadata.ScanlineSize / 2]; Buffer.BlockCopy(scanline, 0, scanline16Bit, 0, scanline.Length); int yStart = (int)Math.Floor((bbox.yMax - metadata.StartLat) / metadata.pixelSizeY); int yEnd = (int)Math.Ceiling((bbox.yMin - metadata.StartLat) / metadata.pixelSizeY); int xStart = (int)Math.Floor((bbox.xMin - metadata.StartLon) / metadata.pixelSizeX); int xEnd = (int)Math.Ceiling((bbox.xMax - metadata.StartLon) / metadata.pixelSizeX); xStart = Math.Max(0, xStart); xEnd = Math.Min(scanline16Bit.Length - 1, xEnd); yStart = Math.Max(0, yStart); yEnd = Math.Min(metadata.Height - 1, yEnd); for (int y = yStart; y <= yEnd; y++) { tiff.TiffFile.ReadScanline(scanline, y); Buffer.BlockCopy(scanline, 0, scanline16Bit, 0, scanline.Length); double latitude = metadata.StartLat + (metadata.pixelSizeY * y); for (int x = xStart; x <= xEnd; x++) { double longitude = metadata.StartLon + (metadata.pixelSizeX * x); float heightValue = (float)scanline16Bit[x]; if (heightValue < 32768) { heightMap.Mininum = Math.Min(heightMap.Mininum, heightValue); heightMap.Maximum = Math.Max(heightMap.Maximum, heightValue); } else { heightValue = NO_DATA_OUT; } heightMap.Coordinates.Add(new GeoPoint(latitude, longitude, heightValue, x, y)); } } return(heightMap); }
public static Image <Color32> Parse(byte[] bytes) { try { var tif = GeoTiff.ImageFromBytes(bytes); if (tif is Image <byte> ) { var img = tif as Image <byte>; var image = new Image <Color32>(); image.Width = img.Width; image.Height = img.Height; image.Channels = img.Channels; image.Data = new Color32[image.Width * image.Height]; for (int i = 0, c = image.Width * image.Height; i < c; ++i) { ref Color32 color = ref image.Data[i]; int index = i * image.Channels; color.r = img.Data[index]; color.g = (image.Channels > 1) ? img.Data[index + 1] : img.Data[index]; color.b = (image.Channels > 2) ? img.Data[index + 2] : img.Data[index]; color.a = (image.Channels > 3) ? img.Data[index + 3] : (byte)255; } return(image); } if (tif is Image <short> ) { var img = tif as Image <short>; var image = new Image <Color32>(); image.Width = img.Width; image.Height = img.Height; image.Channels = img.Channels; image.Data = new Color32[image.Width * image.Height]; for (int i = 0, c = image.Width * image.Height; i < c; ++i) { ref Color32 color = ref image.Data[i]; int index = i * image.Channels; color.r = (byte)(img.Data[index] / 255); color.g = (image.Channels > 1) ? (byte)(img.Data[index + 1] / 255) : (byte)img.Data[index]; color.b = (image.Channels > 2) ? (byte)(img.Data[index + 2] / 255) : (byte)img.Data[index]; color.a = (image.Channels > 3) ? (byte)(img.Data[index + 3] / 255) : (byte)255; } return(image); }
private void selectFileButton_Click(object sender, System.EventArgs e) { traceTextBox.Text = "selected: " + Project.togeotiffFileName; GeoTiff geoTiff = new GeoTiff(Project.togeotiffFileName); geoTiff.TopLeftLat = geoTiff.TopRightLat = CameraManager.This.CoverageTopLeft34.Lat; geoTiff.TopLeftLng = geoTiff.BottomLeftLng = CameraManager.This.CoverageTopLeft34.Lng; geoTiff.BottomRightLat = geoTiff.BottomLeftLat = CameraManager.This.CoverageBottomRight34.Lat; geoTiff.BottomRightLng = geoTiff.TopRightLng = CameraManager.This.CoverageBottomRight34.Lng; geoTiff.initImageOnly(); if (geoTiff.isValid) { CustomMapsCache.RemoveCustomMapsBySource(Project.togeotiffFileName); CustomMap cm = new CustomMapGeotiff(geoTiff); Project.customMapId++; cm.Id = Project.customMapId; CustomMapsCache.AddCustomMap(cm); WaypointsCache.pushBoundaries(cm.Location); WaypointsCache.pushBoundaries(new GeoCoord(geoTiff.BottomLeftLng, geoTiff.BottomLeftLat)); WaypointsCache.pushBoundaries(new GeoCoord(geoTiff.TopRightLng, geoTiff.TopRightLat)); WaypointsCache.pushBoundaries(new GeoCoord(geoTiff.BottomRightLng, geoTiff.BottomRightLat)); string msg = "OK: read image file " + Project.togeotiffFileName; LibSys.StatusBar.Trace(msg); LibSys.StatusBar.Trace("* " + msg); toState(2); selectGeotiffPointButton.Enabled = true; selectMapPointButton.Enabled = false; PictureManager.This.Refresh(); } else { LibSys.StatusBar.Error("cannot make a GeoTIFF file: " + Project.togeotiffFileName); } }
public override BasicInfo GetBasicInfo(string filename) { BasicInfo info = new BasicInfo(); try { var geoTiff = new GeoTiff(filename); info.bounds = geoTiff.Bounds; info.isRaster = true; info.width = geoTiff.Width; info.height = geoTiff.Height; info.degreesPerPixel = geoTiff.GetDegreesPerPixel(); } catch (Exception e) { Debug.LogException(e); return(null); } return(info); }
public override void Execute() { base.Execute(); var tif = GeoTiff.ImageFromBytes(FileBytes); if (tif is Image <byte> ) { var img = tif as Image <byte>; Image.Width = img.Width; Image.Height = img.Height; Image.Channels = img.Channels; Image.Data = new Color32[Image.Width * Image.Height]; for (int i = 0, c = Image.Width * Image.Height; i < c; ++i) { ref Color32 color = ref Image.Data[i]; int index = i * Image.Channels; color.r = img.Data[index]; color.g = (Image.Channels > 1) ? img.Data[index + 1] : img.Data[index]; color.b = (Image.Channels > 2) ? img.Data[index + 2] : img.Data[index]; color.a = (Image.Channels > 3) ? img.Data[index + 3] : (byte)255; } return; }
public override bool Read(string filename, ProgressInfo progress, out PatchData data) { data = null; using (var geoTiff = new GeoTiff(filename)) { if (geoTiff == null) { return(false); } var bouds = geoTiff.Bounds; GridData grid = new GridData { north = bouds.north, east = bouds.east, west = bouds.west, south = bouds.south, }; grid.countX = geoTiff.Width; grid.countY = geoTiff.Height; grid.InitGridValues(false); // Read raster values int width = grid.countX; int height = grid.countY; int bufferSize = width * height; int bytesPerSample = geoTiff.BitsPerSample / 8; var dataType = geoTiff.DataType; if (dataType == null) { switch (geoTiff.BitsPerSample) { case 8: dataType = typeof(byte); break; case 16: dataType = typeof(UInt16); break; case 32: dataType = typeof(UInt32); break; case 64: dataType = typeof(UInt64); break; } } ValueConverter convert = ConverterMap[dataType]; if (geoTiff.Tiff.IsTiled()) { int tileCount = geoTiff.Tiff.NumberOfTiles(); int bytesPerTileRow = geoTiff.Tiff.TileRowSize(); int tileWidth = 0, tileHeight = 0; tileWidth = bytesPerTileRow / bytesPerSample; tileHeight = bytesPerTileRow / bytesPerSample; int tilesPerRow = Mathf.CeilToInt((float)width / tileWidth); int bytesPerTile = geoTiff.Tiff.TileSize(); byte[] buffer = new byte[bytesPerTile]; int offset, index = 0; float progressStep = 1f / tileCount; for (int tile = 0; tile < tileCount; tile++) { geoTiff.Tiff.ReadEncodedTile(tile, buffer, 0, bytesPerTile); int tileX = tile % tilesPerRow; int tileY = tile / tilesPerRow; int xOffset = tileX * tileWidth; int yOffset = tileY * tileHeight; index = yOffset * width + xOffset; offset = 0; int w = Math.Min(width, xOffset + tileWidth) - xOffset; int h = Math.Min(height, yOffset + tileHeight) - yOffset; for (int r = 0; r < h; r++) { for (int c = 0; c < w; c++) { grid.values[index++] = convert(buffer, offset); offset += bytesPerSample; } index += width - w; offset += (tileWidth - w) * bytesPerSample; } progress.value += progressStep; } } else { int scanlineSize = width * bytesPerSample; byte[] buffer = new byte[scanlineSize]; int offset, index = 0; float progressStep = 1f / grid.countY; for (int r = 0; r < height; r++) { offset = 0; geoTiff.Tiff.ReadScanline(buffer, r); for (int c = 0; c < width; c++) { grid.values[index++] = convert(buffer, offset); offset += bytesPerSample; } progress.value += progressStep; } } progress.value = 1; grid.AddMaskValue((float)geoTiff.NoDataValue); var citation = geoTiff.Citation; if (!string.IsNullOrWhiteSpace(citation)) { grid.AddMetadata("Citation", citation); } data = grid; } return(true); }
public static altresponce getAltitude(double lat, double lng, double zoom = 16) { short alt = 0; var trytiff = GeoTiff.getAltitude(lat, lng); if (trytiff.currenttype == tiletype.valid) { return(trytiff); } var trydted = DTED.getAltitude(lat, lng); if (trydted.currenttype == tiletype.valid) { return(trydted); } //lat += 1 / 1199.0; //lng -= 1 / 1201f; // lat -35.115676879882812 double // lng 117.94178754638671 double // alt 70 short var filename = GetFilename(lat, lng); if (String.IsNullOrEmpty(filename)) { return(altresponce.Invalid); } try { if (cache.ContainsKey(filename) || File.Exists(datadirectory + Path.DirectorySeparatorChar + filename)) { // srtm hgt files int size = -1; // add to cache if (!cache.ContainsKey(filename)) { using ( FileStream fs = new FileStream(datadirectory + Path.DirectorySeparatorChar + filename, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fs.Length == (1201 * 1201 * 2)) { size = 1201; } else if (fs.Length == (3601 * 3601 * 2)) { size = 3601; } else { return(srtm.altresponce.Invalid); } byte[] altbytes = new byte[2]; short[,] altdata = new short[size, size]; int altlat = 0; int altlng = 0; while (fs.Read(altbytes, 0, 2) != 0) { altdata[altlat, altlng] = (short)((altbytes[0] << 8) + altbytes[1]); altlat++; if (altlat >= size) { altlng++; altlat = 0; } } cache[filename] = altdata; } } if (cache[filename].Length == (1201 * 1201)) { size = 1201; } else if (cache[filename].Length == (3601 * 3601)) { size = 3601; } else { return(srtm.altresponce.Invalid); } int x = (lng < 0) ? (int)(lng - 1) : (int)lng; int y = (lat < 0) ? (int)(lat - 1) : (int)lat; // remove the base lat long lat -= y; lng -= x; // values should be 0-1199, 1200 is for interpolation double xf = lng * (size - 2); double yf = lat * (size - 2); int x_int = (int)xf; double x_frac = xf - x_int; int y_int = (int)yf; double y_frac = yf - y_int; y_int = (size - 2) - y_int; double alt00 = GetAlt(filename, x_int, y_int); double alt10 = GetAlt(filename, x_int + 1, y_int); double alt01 = GetAlt(filename, x_int, y_int + 1); double alt11 = GetAlt(filename, x_int + 1, y_int + 1); double v1 = avg(alt00, alt10, x_frac); double v2 = avg(alt01, alt11, x_frac); double v = avg(v1, v2, -y_frac); if (v < -1000) { return(altresponce.Invalid); } return(new altresponce() { currenttype = tiletype.valid, alt = v, altsource = "SRTM" }); } string filename2 = "srtm_" + Math.Round((lng + 2.5 + 180) / 5, 0).ToString("00") + "_" + Math.Round((60 - lat + 2.5) / 5, 0).ToString("00") + ".asc"; if (File.Exists(datadirectory + Path.DirectorySeparatorChar + filename2)) { using ( StreamReader sr = new StreamReader(readFile(datadirectory + Path.DirectorySeparatorChar + filename2))) { int nox = 0; int noy = 0; float left = 0; float top = 0; int nodata = -9999; float cellsize = 0; int rowcounter = 0; float wantrow = 0; float wantcol = 0; while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.StartsWith("ncols")) { nox = int.Parse(line.Substring(line.IndexOf(' '))); //hgtdata = new int[nox * noy]; } else if (line.StartsWith("nrows")) { noy = int.Parse(line.Substring(line.IndexOf(' '))); //hgtdata = new int[nox * noy]; } else if (line.StartsWith("xllcorner")) { left = float.Parse(line.Substring(line.IndexOf(' '))); } else if (line.StartsWith("yllcorner")) { top = float.Parse(line.Substring(line.IndexOf(' '))); } else if (line.StartsWith("cellsize")) { cellsize = float.Parse(line.Substring(line.IndexOf(' '))); } else if (line.StartsWith("NODATA_value")) { nodata = int.Parse(line.Substring(line.IndexOf(' '))); } else { string[] data = line.Split(new char[] { ' ' }); if (data.Length == (nox + 1)) { wantcol = (float)((lng - Math.Round(left, 0))); wantrow = (float)((lat - Math.Round(top, 0))); wantrow = (int)(wantrow / cellsize); wantcol = (int)(wantcol / cellsize); wantrow = noy - wantrow; if (rowcounter == wantrow) { Console.WriteLine("{0} {1} {2} {3} ans {4} x {5}", lng, lat, left, top, data[(int)wantcol], (nox + wantcol * cellsize)); return(new altresponce() { currenttype = tiletype.valid, alt = int.Parse(data[(int)wantcol]) }); } rowcounter++; } } } } return(new altresponce() { currenttype = tiletype.valid, alt = alt, altsource = "ASCII" }); } else // get something { if (filename.Contains("S00W000") || filename.Contains("S00W001") || filename.Contains("S01W000") || filename.Contains("S01W001")) { return(altresponce.Ocean); } if (oceantile.Contains(filename)) { return(altresponce.Ocean); } if (zoom >= 7) { if (!Directory.Exists(datadirectory)) { Directory.CreateDirectory(datadirectory); } if (requestThread == null) { // log.Info("Getting " + filename); lock (objlock) { queue.Add(filename); } requestThread = new Thread(requestRunner); requestThread.IsBackground = true; requestThread.Name = "SRTM request runner"; requestThread.Start(); } else { lock (objlock) { if (!queue.Contains(filename)) { //log.Info("Getting " + filename); queue.Add(filename); } } } } } } catch (Exception ex) { //log.Error(ex); return(altresponce.Invalid); } return(altresponce.Invalid); }
public void WriteImage(string filename) { var bytes = GeoTiff.BytesFromImage(Image); System.IO.File.WriteAllBytes(filename, bytes); }