管道基础大数据平台系统开发-【CS】-ExportMap
13693261870
2024-07-19 402fdc4cb6f94016cf9749bb1f09a6c5ead5d6d3
添加重采样功能
已添加1个文件
已修改4个文件
289 ■■■■■ 文件已修改
SimuTools/App.config 4 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SimuTools/SimuTools.csproj 1 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SimuTools/Tools/GdalHelper.cs 9 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SimuTools/Tools/Handle.cs 107 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
SimuTools/Tools/tiffConvert.py 168 ●●●●● 补丁 | 查看 | 原始文档 | 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)