SimuTools/App.config | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
SimuTools/SimuTools.csproj | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
SimuTools/Tools/GdalHelper.cs | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
SimuTools/Tools/Handle.cs | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 | |
SimuTools/Tools/tiffConvert.py | ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史 |
SimuTools/App.config
@@ -1,8 +1,12 @@ <?xml version="1.0"?> <configuration> <appSettings> <!--çæ¬å·--> <add key="ver" value="0.1"/> <!--å辨çï¼64,128,256,512,1024,2048 --> <add key="sizes" value="64,128,256,512,1024,2048"/> <!-- GDALè·¯å¾ --> <add key="gdalPath" value="E:\terrait\TianJin\Zip\release-1928-x64-dev\release-1928-x64\bin\" /> </appSettings> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/> SimuTools/SimuTools.csproj
@@ -556,6 +556,7 @@ <DependentUpon>Settings.settings</DependentUpon> <DesignTimeSharedInput>True</DesignTimeSharedInput> </Compile> <None Include="Tools\tiffConvert.py" /> </ItemGroup> <ItemGroup> <None Include="App.config" /> SimuTools/Tools/GdalHelper.cs
@@ -180,7 +180,7 @@ /// <summary> /// å建PNG /// </summary> public void CreatePng(string filePath, int width, int height, int bands = 3) public void CreatePng(byte[] buffer, string filePath, int width, int height, int bands = 3) { // å建å åé©±å¨ OSGeo.GDAL.Driver memDriver = Gdal.GetDriverByName("MEM"); @@ -192,13 +192,6 @@ { Band band = ds.GetRasterBand(i); band.SetRasterColorInterpretation((ColorInterp)i); } // å¡«å å åå¾å byte[] buffer = new byte[width * height * bands]; for (int i = 0; i < buffer.Length; i++) { buffer[i] = (byte)(i % 256); } // åå ¥å åå¾å SimuTools/Tools/Handle.cs
@@ -4,6 +4,8 @@ using SimuTools.Domain; using System; using System.Collections.Generic; using System.Configuration; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; @@ -13,6 +15,8 @@ { public class Handle { public static readonly string GdalPath = ConfigurationManager.AppSettings["gdalPath"]; public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; /// <summary> @@ -25,10 +29,15 @@ layer.terrain = new Terrain(); layer.waters = new Water(); string temp = Path.Combine(outPath, "temp"); if (!Directory.Exists(temp)) Directory.CreateDirectory(temp); CopeTerrain(terrainFile, outPath, layer); CopeWater(waterPath, outPath, layer); CopeFlow(flowPath, outPath, layer); CopeLayerJson(outPath, layer); //if (Directory.Exists(temp)) Directory.Delete(temp, true); } /// <summary> @@ -60,7 +69,7 @@ Geometry maxPoint = GdalHelper.GetMaxPoint(ds); layer.extension = new Extension(minPoint.GetX(0), minPoint.GetY(0), maxPoint.GetX(0), maxPoint.GetY(0)); Band band = ds.GetRasterBand(1); OSGeo.GDAL.Band band = ds.GetRasterBand(1); double[] mm = new double[2]; band.ComputeRasterMinMax(mm, 0); layer.extension.SetHeight(mm[0], mm[1]); @@ -71,10 +80,81 @@ /// </summary> private static void CreateTerrainPng(Dataset ds, Domain.Layer layer, string outPath) { string tempPath = Path.Combine(outPath, "temp"); if (!Directory.Exists(tempPath)) Directory.CreateDirectory(tempPath); string terrainPath = Path.Combine(outPath, "terrain"); if (!Directory.Exists(terrainPath)) Directory.CreateDirectory(terrainPath); foreach (int[] sizes in layer.terrain.size) { //string filePath = Path.Combine(outPath, sizes[0] + "_" + sizes[1] + ".png"); //// å¡«å å åå¾å //byte[] buffer = new byte[sizes[0] * sizes[1] * 3]; //for (int i = 0; i < buffer.Length; i++) //{ // buffer[i] = (byte)(i % 256); //} string tif = Path.Combine(tempPath, DateTime.Now.Ticks.ToString() + ".tif"); Resample(ds.GetDescription(), tif, sizes[0], sizes[1]); if (!File.Exists(tif)) { continue; } // } } /// <summary> /// ééæ · /// </summary> private static void Resample(string source, string dest, int width, int height) { string cmd = string.Format("{0}gdalwarp.exe -t_srs {1} -ts {2} {3} -r {4} -of GTiff \"{5}\" \"{6}\"", GdalPath, "EPSG:4326", width, height, "bilinear", source, dest); string err = ExecExe(cmd); } /// <summary> /// æ§è¡å½ä»¤ /// </summary> public static string ExecExe(string cmd) { string str = null; Process p = null; try { p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardError = true; p.Start(); StreamWriter si = p.StandardInput; StreamReader se = p.StandardError; si.AutoFlush = true; si.WriteLine(cmd); si.WriteLine("exit"); str = se.ReadToEnd(); se.Close(); si.Close(); } catch (Exception ex) { LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); str = ex.Message; } finally { if (p != null) p.Close(); } return str; } /// <summary> @@ -108,5 +188,30 @@ sw.Write(json); } } #region ææ¶ä¸ç¨ /// <summary> /// ééæ · * /// </summary> private static void Resample(Dataset ds, string dest, int width, int height) { // 设置Warpçé项ï¼https://blog.csdn.net/qq_43210879/article/details/121350561 string[] options = new string[] { "format=GTiff", "width=" + width, "height=" + height, "dstSRS=EPSG:4326" }; OSGeo.GDAL.Driver driver = Gdal.GetDriverByName("GTiff"); Dataset destDs = driver.Create(dest, width, height, ds.RasterCount, ds.GetRasterBand(1).DataType, null); GDALWarpAppOptions warpAppOptions = new GDALWarpAppOptions(options); Gdal.Warp(destDs, new Dataset[] { ds }, warpAppOptions, null, null); destDs.Dispose(); } #endregion } } SimuTools/Tools/tiffConvert.py
¶Ô±ÈÐÂÎļþ @@ -0,0 +1,168 @@ from osgeo import gdal from PIL import Image import numpy as np import os import datetime def print_with_timestamp(message): # è·åå½åæ¶é´ current_time = datetime.datetime.now() # æ ¼å¼åæ¶é´æ³ timestamp = current_time.strftime("%Y-%m-%d %H:%M:%S") # æå°å¸¦ææ¶é´æ³çæ¶æ¯ print(f"[{timestamp}] {message}") def reproject_and_resample_tiff(tiff_path, output_tiff_path, target_epsg, factor): # æå¼TIFFæä»¶ dataset = gdal.Open(tiff_path, gdal.GA_ReadOnly) if dataset is None: print_with_timestamp(f"æ æ³æå¼TIFFæä»¶: {tiff_path}") return # è·åTIFFæä»¶ç宽度åé«åº¦ width = dataset.RasterXSize height = dataset.RasterYSize # 计ç®ééæ ·åç宽度åé«åº¦ new_width = int(width / factor) new_height = int(height / factor) # 设置éæå½±åééæ ·åæ° options = gdal.WarpOptions( format='GTiff', width=new_width, height=new_height, dstSRS=f'EPSG:{target_epsg}', resampleAlg=gdal.GRA_Bilinear ) filename = os.path.basename(tiff_path) output_path = os.path.join(output_tiff_path,filename) # æ§è¡éæå½±åééæ · gdal.Warp(output_path, dataset, options=options) print_with_timestamp(f"å·²å°TIFFæä»¶éæå½±å¹¶ééæ ·å°: {output_path}") return output_path def tiff_to_png(tiff_path, png_path, waterFlag, imageFlag): # æå¼éæå½±åééæ ·åçTIFFæä»¶ dataset = gdal.Open(tiff_path, gdal.GA_ReadOnly) if dataset is None: print_with_timestamp(f"æ æ³æå¼TIFFæä»¶:{tiff_path}") return # è·åTIFFæä»¶ç宽度åé«åº¦ width = dataset.RasterXSize height = dataset.RasterYSize # è·åTIFFæä»¶çé«åº¦æ°æ® band = dataset.GetRasterBand(1) heights = band.ReadAsArray() # mask_a = heights > -32766 # heights = mask_a * heights # æé«é«åº¦,è¦æ¯æµè¯æ°æ®çæé«å¤21é« maxHeight = 23 # å建ä¸ä¸ªç©ºç½çPNGå¾å image = Image.new("RGB", (width, height)) # image = Image.new("L", (width, height)) # å建äºç»´æ°ç» array = np.zeros((width, height), dtype="<i2") # å°æ¯ä¸ªåç´ çRGBå¼è®¾ç½®ä¸ºé«åº¦çç°åº¦å¼ for y in range(height): for x in range(width): # è·å该ä½ç½®çé«åº¦å¼ height_value = heights[y, x] alpha = 255 if height_value <= 0: height_value = 0 if waterFlag else maxHeight elif np.isnan(height_value): height_value = 0 if waterFlag else maxHeight else: height_value = height_value + 1.0 if waterFlag else height_value if imageFlag: # å°é«åº¦å¼æ å°å°RGBå¼ï¼ç°åº¦ï¼ï¼æé«å¼ä»¥30为å gray_value = int((height_value / maxHeight) * 255) # å¨PNGå¾åä¸è®¾ç½®åç´ çRGBå¼ # image.putpixel((x, y), (gray_value, gray_value, gray_value, alpha)) image.putpixel((x, y), (gray_value, gray_value, gray_value)) # image.putpixel((x, y), gray_value) else: # å°æ°å¼ç²¾ç¡®å°åç±³ï¼ä¿åæäºè¿å¶çäºç»´æ°ç», é«ç¨åæ°´é¢çåç±³è¡¨ç¤ºè¦æ§å¶å¨65535ä¹å height_value = int(height_value * 100) # 精确å°å°æ°å两ä½ï¼åç±³ array[x][y] = height_value # ä¿åPNGå¾å if imageFlag: image.save(png_path) print_with_timestamp(f"å·²å°TIFFæä»¶è½¬æ¢ä¸ºPNG: {png_path}") else: # å°äºç»´æ°ç»ä¿å为äºè¿å¶æä»¶ # ä½¿ç¨ 'w' 模å¼åå ¥æä»¶ï¼'b' 表示以äºè¿å¶å½¢å¼ with open(png_path, 'wb') as f: # tobytes() æ¹æ³å°æ°ç»å ç´ æå åä¸ç顺åºè½¬æ¢æä¸ä¸ªåè串 f.write(array.tobytes()) print_with_timestamp(f"å·²å°TIFFæä»¶è½¬æ¢ä¸ºBIN: {png_path}") def list_tif_files(directory,tif_files): # éåæå®ç®å½ä¸çæææä»¶ååç®å½ for root, dirs, files in os.walk(directory): for file in files: # æ£æ¥æä»¶æ¯å¦ä»¥.tifç»å°¾ if file.lower().endswith('.tif'): # å°å®æ´è·¯å¾æ·»å å°åè¡¨ä¸ path = os.path.join(root,file) print_with_timestamp(f"è¯å«å°tiffæä»¶ï¼{path}") tif_files.append(os.path.join(root, file)) return tif_files def main(imageFlag): # 设置è¾å ¥TIFFæä»¶è·¯å¾ input_tiff_path = ".\\tiff28" # 设置éæå½±åééæ ·åçTIFFæä»¶è·¯å¾ output_tiff_path = ".\\resample" # è®¾ç½®ç®æ EPSG代ç target_epsg = 4326 # WGS84 # 设置ééæ ·å å factor = 10 # 设置è¾åºå«æ°´é¢é«åº¦å¾PNGæä»¶è·¯å¾ output_water_png_path = ".\\waterImage" # 设置è¾åºä¸å«æ°´é¢çå°å½¢ã建çé«åº¦å¾PNGæä»¶è·¯å¾ output_terrain_png_path = ".\\terrainImage" # å建ä¸ä¸ªç©ºå表æ¥å卿æç.tifæä»¶ tif_files = [] # éåæä»¶å¤¹ä¸çtiff list_tif_files(input_tiff_path, tif_files) for file in tif_files: print_with_timestamp(f"{file} å¼å§éæå½±") # æ§è¡éæå½±åééæ · out_path = reproject_and_resample_tiff(file, output_tiff_path, target_epsg, factor) print_with_timestamp(f"{out_path} å¼å§è½¬æ¢ä¸ºpng") # 使ç¨os.path.basenameæ¹æ³è·åè·¯å¾ä¸çæä»¶å file_name = os.path.basename(out_path) # 使ç¨os.path.splitextæ¹æ³å离æä»¶ååæ©å±å file_name_without_ext, _ = os.path.splitext(file_name) # æ°´é¢é«åº¦å¾è·¯å¾ out_water_png_file = os.path.join(output_water_png_path, file_name_without_ext) out_water_png_file = f"{out_water_png_file}.png" if imageFlag else f"{out_water_png_file}.bin" # å°å½¢&建çé«åº¦å¾è·¯å¾ out_terrain_png_file = os.path.join(output_terrain_png_path, file_name_without_ext) out_terrain_png_file = f"{out_terrain_png_file}.png" if imageFlag else f"{out_terrain_png_file}.bin" # å°éæå½±åééæ ·åç带水é¢çTIFFæä»¶è½¬æ¢ä¸ºé«åº¦å¾PNG tiff_to_png(out_path, out_water_png_file, True, imageFlag) # å°éæå½±åééæ ·åçä¸å¸¦æ°´é¢çTIFFæä»¶è½¬æ¢ä¸ºé«åº¦å¾PNG # tiff_to_png(out_path, out_terrain_png_file, False, imageFlag) if __name__ == "__main__": main(True)