From 402fdc4cb6f94016cf9749bb1f09a6c5ead5d6d3 Mon Sep 17 00:00:00 2001 From: 13693261870 <252740454@qq.com> Date: 星期五, 19 七月 2024 12:43:30 +0800 Subject: [PATCH] 添加重采样功能 --- SimuTools/Tools/GdalHelper.cs | 9 - SimuTools/SimuTools.csproj | 1 SimuTools/App.config | 4 SimuTools/Tools/tiffConvert.py | 168 +++++++++++++++++++++++++++++++++ SimuTools/Tools/Handle.cs | 107 +++++++++++++++++++++ 5 files changed, 280 insertions(+), 9 deletions(-) diff --git a/SimuTools/App.config b/SimuTools/App.config index d53e0be..c2ceb05 100644 --- a/SimuTools/App.config +++ b/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"/> diff --git a/SimuTools/SimuTools.csproj b/SimuTools/SimuTools.csproj index b5464f0..65be7b8 100644 --- a/SimuTools/SimuTools.csproj +++ b/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" /> diff --git a/SimuTools/Tools/GdalHelper.cs b/SimuTools/Tools/GdalHelper.cs index 0a6e6ba..c579e01 100644 --- a/SimuTools/Tools/GdalHelper.cs +++ b/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); } // 鍐欏叆鍐呭瓨鍥惧儚 diff --git a/SimuTools/Tools/Handle.cs b/SimuTools/Tools/Handle.cs index da4768d..555cb3c 100644 --- a/SimuTools/Tools/Handle.cs +++ b/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鐨勯�夐」锛歨ttps://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 } } diff --git a/SimuTools/Tools/tiffConvert.py b/SimuTools/Tools/tiffConvert.py new file mode 100644 index 0000000..d67093c --- /dev/null +++ b/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): + # 鎵撳紑閲嶆姇褰卞拰閲嶉噰鏍峰悗鐨凾IFF鏂囦欢 + 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) + # 鍦≒NG鍥惧儚涓缃儚绱犵殑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鏂囦欢杞崲涓篜NG: {png_path}") + else: + # 灏嗕簩缁存暟缁勪繚瀛樹负浜岃繘鍒舵枃浠� + # 浣跨敤 'w' 妯″紡鍐欏叆鏂囦欢锛�'b' 琛ㄧず浠ヤ簩杩涘埗褰㈠紡 + with open(png_path, 'wb') as f: + # tobytes() 鏂规硶灏嗘暟缁勫厓绱犳寜鍐呭瓨涓殑椤哄簭杞崲鎴愪竴涓瓧鑺備覆 + f.write(array.tobytes()) + print_with_timestamp(f"宸插皢TIFF鏂囦欢杞崲涓築IN: {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"璇嗗埆鍒皌iff鏂囦欢锛歿path}") + tif_files.append(os.path.join(root, file)) + + return tif_files + +def main(imageFlag): + # 璁剧疆杈撳叆TIFF鏂囦欢璺緞 + input_tiff_path = ".\\tiff28" + # 璁剧疆閲嶆姇褰卞拰閲嶉噰鏍峰悗鐨凾IFF鏂囦欢璺緞 + output_tiff_path = ".\\resample" + # 璁剧疆鐩爣EPSG浠g爜 + target_epsg = 4326 # WGS84 + # 璁剧疆閲嶉噰鏍峰洜瀛� + factor = 10 + + # 璁剧疆杈撳嚭鍚按闈㈤珮搴﹀浘PNG鏂囦欢璺緞 + output_water_png_path = ".\\waterImage" + # 璁剧疆杈撳嚭涓嶅惈姘撮潰鐨勫湴褰€�佸缓绛戦珮搴﹀浘PNG鏂囦欢璺緞 + output_terrain_png_path = ".\\terrainImage" + + # 鍒涘缓涓�涓┖鍒楄〃鏉ュ瓨鍌ㄦ墍鏈夌殑.tif鏂囦欢 + tif_files = [] + + # 閬嶅巻鏂囦欢澶逛腑鐨則iff + 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) + # 灏嗛噸鎶曞奖鍜岄噸閲囨牱鍚庣殑涓嶅甫姘撮潰鐨凾IFF鏂囦欢杞崲涓洪珮搴﹀浘PNG + # tiff_to_png(out_path, out_terrain_png_file, False, imageFlag) + +if __name__ == "__main__": + main(True) \ No newline at end of file -- Gitblit v1.9.3