AB版本数据
parent
6d094f5dad
commit
3200877d25
|
|
@ -0,0 +1,5 @@
|
|||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
|
|
@ -0,0 +1 @@
|
|||
PredictProcessRaster.py
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="jdk" jdkName="Python 3.9" jdkType="Python SDK" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="GOOGLE" />
|
||||
<option name="myDocStringFormat" value="Google" />
|
||||
</component>
|
||||
</module>
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="Black">
|
||||
<option name="sdkName" value="spacetySliceEnv" />
|
||||
</component>
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.9" project-jdk-type="Python SDK" />
|
||||
</project>
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/SpacetySliceDataTools.iml" filepath="$PROJECT_DIR$/.idea/SpacetySliceDataTools.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
import argparse
|
||||
########################################################
|
||||
# 函数区
|
||||
########################################################
|
||||
|
||||
spacetySliceEnvPathExEPath=r"D:\ProgramData\miniconda3\envs\spacetySliceEnv\python.exe"
|
||||
|
||||
def find_tif_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.bin'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def find_txt_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.txt'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def matchTiff_Txt(tiffpaths,txtPaths):
|
||||
match_results={}
|
||||
tiffID=0
|
||||
for tid in range(len(tiffpaths)):
|
||||
tiffID=tiffID+1
|
||||
match_results[tiffID]={"tiff":tiffpaths[tid],"txt":[]}
|
||||
rootname=Path(tiffpaths[tid]).stem
|
||||
for txtpath in txtPaths:
|
||||
txtrootname=Path(txtpath).stem
|
||||
if txtrootname.startswith(rootname):
|
||||
match_results[tiffID]["txt"].append(txtpath)
|
||||
|
||||
return match_results
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inbinfile',type=str,default=r'D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01.tiff', help='输入tiff的bin文件')
|
||||
parser.add_argument('-l', '--labelfilepath',type=str,default=r"D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01_LC.txt", help='输入标注')
|
||||
parser.add_argument('-o', '--outfolderpath',type=str,default=r'D:\Annotation_Y\结果文件', help='切片文件夹地址')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
|
@ -0,0 +1,175 @@
|
|||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
import hashlib # md5
|
||||
import time
|
||||
import shutil
|
||||
import datetime
|
||||
########################################################
|
||||
# 函数区
|
||||
########################################################
|
||||
|
||||
spacetySliceEnvPathExEPath=r"d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe"
|
||||
|
||||
def find_tif_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.tif')) + list(path.rglob('*.tiff'))
|
||||
|
||||
seemname=set()
|
||||
tiffpaths=[]
|
||||
for tiffpath in tif_files:
|
||||
tiffpath =str(tiffpath)
|
||||
rootname = Path(tiffpath).stem
|
||||
if rootname not in seemname:
|
||||
seemname.add(rootname)
|
||||
tiffpaths.append(tiffpath)
|
||||
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tiffpaths]
|
||||
|
||||
|
||||
def find_shp_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.shp'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
def preProcessTiFF(tiffpath,preFolderPath):
|
||||
|
||||
file_path = Path(tiffpath)
|
||||
directory_path = str(file_path.resolve().parent.name)
|
||||
rootname=Path(tiffpath).stem
|
||||
outpngpath=os.path.join(preFolderPath,"I"+directory_path+"_"+rootname+'.png')
|
||||
programpath=r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py"
|
||||
|
||||
# cmdtxt=r"{} {} -i {} -o {} --filemode --SquareRoot".format(spacetySliceEnvPathExEPath,programpath,tiffpath,outpngpath)
|
||||
cmdtxt=r"{} {} -i {} -o {} --slicemode --SquareRoot".format(spacetySliceEnvPathExEPath,programpath,tiffpath,preFolderPath) # 直接切片
|
||||
if os.system(cmdtxt) ==2:
|
||||
print("sucess:",cmdtxt)
|
||||
return "sucess: {}".format(cmdtxt)
|
||||
else:
|
||||
print("failed:",cmdtxt)
|
||||
return "failed: {}".format(cmdtxt)
|
||||
pass
|
||||
|
||||
|
||||
def moveDir(srcfolderPath,targetfolderPath):
|
||||
try:
|
||||
shutil.copytree(srcfolderPath,targetfolderPath,dirs_exist_ok=True)
|
||||
print("sucess: copy ", srcfolderPath,targetfolderPath )
|
||||
shutil.rmtree(srcfolderPath)
|
||||
print("sucess: rmtree ", srcfolderPath)
|
||||
return "sucess: copy and rmtree from {} to {}".format(srcfolderPath,targetfolderPath),True
|
||||
except Exception as e:
|
||||
print("failed: copy ", srcfolderPath, targetfolderPath)
|
||||
return "failed: copy and rmtree from {} to {}".format(srcfolderPath,targetfolderPath),False
|
||||
|
||||
def writeoutlog(logPath,cmdtxt):
|
||||
with open(logPath,'a',encoding="utf-8") as f:
|
||||
f.write(cmdtxt)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
|
||||
def processPool(srcFolderPath,preFolderPath,targetfolderPath,logPath=r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\log\process.log"):
|
||||
writeoutlog(logPath, "====================================================================================\n")
|
||||
writeoutlog(logPath, "time: {}".format(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")))
|
||||
writeoutlog(logPath, "srcFolderPath: {}".format(srcFolderPath))
|
||||
writeoutlog(logPath, "preFolderPath: {}".format(preFolderPath))
|
||||
writeoutlog(logPath, "process start \n")
|
||||
|
||||
# 1. 预处理流程
|
||||
async_results = []
|
||||
with Pool(processes=6) as pool:
|
||||
movepool=[]
|
||||
# 20250813-不分类 条带模式
|
||||
# srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250813-不分类\0-原图"
|
||||
tiffPaths = find_tif_files_pathlib(srcFolderPath)
|
||||
# preFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250813-不分类\A-预处理\AB-图像预处理"
|
||||
for tiffpath in tiffPaths:
|
||||
async_results.append(
|
||||
pool.apply_async(preProcessTiFF, (tiffpath,preFolderPath,))
|
||||
)
|
||||
|
||||
for pidx in range(len(async_results)):
|
||||
async_result=async_results[pidx]
|
||||
print("{}/{}".format(pidx+1,len(async_results)),async_result.get())
|
||||
writeoutlog(logPath,"{}/{} {}".format(pidx+1,len(async_results),async_result.get()))
|
||||
writeoutlog(logPath, "\nprocess finished \n")
|
||||
moverTip,moveflag=moveDir(preFolderPath, targetfolderPath)
|
||||
writeoutlog(logPath, moverTip)
|
||||
|
||||
writeoutlog(logPath, "====================================================================================\n")
|
||||
if moveflag:
|
||||
pass
|
||||
else:
|
||||
exit(3)
|
||||
|
||||
########################################################
|
||||
# 流程执行区
|
||||
########################################################
|
||||
if __name__ == '__main__':
|
||||
logPath = r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\log\process.log"
|
||||
|
||||
# 20250813-不分类 条带模式
|
||||
# srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250813-不分类\0-原图"
|
||||
# preFolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250813-不分类\A-预处理\AB-图像预处理"
|
||||
# targetfolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250813-不分类\A-预处理\AB-图像预处理"
|
||||
# processPool(srcFolderPath, preFolderPath, targetfolderPath,logPath)
|
||||
#
|
||||
# # 20250818 条带模式
|
||||
# srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250818-不分类\0-原图"
|
||||
# preFolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250818-不分类\A-预处理\AB-图像预处理"
|
||||
# targetfolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250818-不分类\A-预处理\AB-图像预处理"
|
||||
# processPool(srcFolderPath, preFolderPath,targetfolderPath, logPath)
|
||||
#
|
||||
# 20250826-不分类 条带模式
|
||||
srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250826-不分类\0-原图"
|
||||
preFolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250826-不分类\A-预处理\AB-图像预处理"
|
||||
targetfolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250826-不分类\A-预处理\AB-图像预处理"
|
||||
processPool(srcFolderPath, preFolderPath, targetfolderPath,logPath)
|
||||
|
||||
# 20250903-不分类 条带模式
|
||||
srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图"
|
||||
preFolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理"
|
||||
targetfolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理"
|
||||
processPool(srcFolderPath, preFolderPath,targetfolderPath, logPath)
|
||||
|
||||
# # 20250910-不分类 条带模式
|
||||
# srcFolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\0-原图"
|
||||
# preFolderPath = r"D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\A-预处理\AB-图像预处理"
|
||||
# targetfolderPath = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\A-预处理\AB-图像预处理"
|
||||
# processPool(srcFolderPath, preFolderPath, targetfolderPath,logPath)
|
||||
|
||||
|
||||
result_flag_txt = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\strechResult_finish.log"
|
||||
with open(result_flag_txt,"w",encoding="utf-8") as f:
|
||||
f.write("strech finied!!!\n")
|
||||
writeoutlog(logPath, "strech finied!!!\n")
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,79 @@
|
|||
# 统计结果
|
||||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
import argparse
|
||||
|
||||
|
||||
|
||||
|
||||
def find_txt_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.txt'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
def statictNumber(inlabelfilepath):
|
||||
with open(inlabelfilepath,"r",encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
lineresult=[]
|
||||
for l in lines:
|
||||
if len(l) > 10:
|
||||
lineresult.append(l)
|
||||
return len(lineresult)
|
||||
|
||||
|
||||
def StaticProcess(inlabelfolder,outcsvpath):
|
||||
labelfilepaths=find_txt_files_pathlib(inlabelfolder)
|
||||
with open(outcsvpath,"w",encoding="utf-8") as f:
|
||||
f.write("切片名,军用飞机,民用飞机,军民一体飞机,军用轮船,民用轮船,民用机场,军用机场,军民一体机场,军用港口,民用港口,军民一体港口,总计\n")
|
||||
f.write("标注,military_airplane, civil_airplane,mix_airpllane,military_ship,civil_ship,civil_airport,military_airport,mix_airport,military_harbor,civil_harbor,mix_harbor,Total\n")
|
||||
|
||||
for labelfilepath in labelfilepaths:
|
||||
rastername=Path(labelfilepath).stem
|
||||
JFJ=0
|
||||
MFJ=0
|
||||
JMFJ=0
|
||||
JLC=0
|
||||
MLC=statictNumber(labelfilepath)
|
||||
MJC=0
|
||||
JJC=0
|
||||
JMJC=0
|
||||
JGK=0
|
||||
MGK=0
|
||||
JMGK=0
|
||||
Total=JFJ+MFJ+JMFJ+JLC+MLC+MJC+JJC+JMJC+JGK+MGK+JMGK
|
||||
f.write(
|
||||
"{}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}, {}\n".format(
|
||||
# SAR影像名,StudentID,work_time,JFJ,MFJ,JMFJ,JLC,MLC,MJC,JJC,JMJC,JGK,MGK,JMGK,LD,DD,SB,HL,FL,JS,HP,SY,Total
|
||||
rastername,JFJ,MFJ,JMFJ,JLC,MLC,MJC,JJC,JMJC,JGK,MGK,JMGK,Total
|
||||
))
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inlabelfolder',type=str,default=r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\删除空标注', help='输入tiff的bin文件')
|
||||
parser.add_argument('-o', '--outcsvpath',type=str,default=r'D:\TYSAR-德清院\切片对应目标的个数信息表_0919.csv', help='切片文件夹地址')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = getParams()
|
||||
inlabelfolder = args.inlabelfolder
|
||||
outcsvpath = args.outcsvpath
|
||||
print('inlabelfolder:', inlabelfolder)
|
||||
print('outcsvpath:', outcsvpath)
|
||||
StaticProcess(inlabelfolder,outcsvpath)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,129 @@
|
|||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
########################################################
|
||||
# 函数区
|
||||
########################################################
|
||||
|
||||
spacetySliceEnvPathExEPath=r"D:\ProgramData\miniconda3\envs\spacetySliceEnv\python.exe"
|
||||
|
||||
def find_tif_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.tif')) + list(path.rglob('*.tiff'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def find_shp_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.shp'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
def preProcessTiFF(tiffpath,preFolderPath):
|
||||
if not os.path.exists(preFolderPath):
|
||||
os.makedirs(preFolderPath)
|
||||
file_path = Path(tiffpath)
|
||||
directory_path = str(file_path.resolve().parent.name)
|
||||
rootname=Path(tiffpath).stem
|
||||
outpngpath=os.path.join(preFolderPath,"I"+directory_path+"_"+rootname+'.png')
|
||||
programpath=r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py"
|
||||
|
||||
cmdtxt=r"{} {} -i {} -o {} --filemode --SquareRoot".format(spacetySliceEnvPathExEPath,programpath,tiffpath,outpngpath)
|
||||
if os.system(cmdtxt) ==2:
|
||||
print("sucess:",cmdtxt)
|
||||
return "sucess: {}".format(cmdtxt)
|
||||
else:
|
||||
print("failed:",cmdtxt)
|
||||
return "failed: {}".format(cmdtxt)
|
||||
pass
|
||||
|
||||
def preProcessLabelshapefile(shpfilepath,preFolderPath):
|
||||
if not os.path.exists(preFolderPath):
|
||||
os.makedirs(preFolderPath)
|
||||
file_path = Path(shpfilepath)
|
||||
directory_path = str(file_path.resolve().parent.name)
|
||||
|
||||
rootname = Path(shpfilepath).stem
|
||||
txtpath=os.path.join(preFolderPath,r"I"+directory_path+"_"+rootname+'.txt')
|
||||
programpath=r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\shapefile2dota.py"
|
||||
cmdtxt=r"{} {} -i {} -o {}".format(spacetySliceEnvPathExEPath,programpath,shpfilepath,txtpath)
|
||||
if os.system(cmdtxt) ==2:
|
||||
print("sucess:",cmdtxt)
|
||||
return "sucess: {}".format(cmdtxt)
|
||||
else:
|
||||
print("failed:",cmdtxt)
|
||||
return "failed: {}".format(cmdtxt)
|
||||
pass
|
||||
|
||||
|
||||
########################################################
|
||||
# 流程执行区
|
||||
########################################################
|
||||
if __name__ == '__main__':
|
||||
|
||||
# 1. 预处理流程
|
||||
async_results = []
|
||||
with Pool() as pool:
|
||||
# 聚束模式
|
||||
srcFolderPath = r"D:\Annotation_Y\港口\聚束模式"
|
||||
tiffPaths = find_tif_files_pathlib(srcFolderPath)
|
||||
shpPaths = find_shp_files_pathlib(srcFolderPath)
|
||||
preFolderPath = r"D:\Annotation_Y\预处理\聚束模式"
|
||||
for tiffpath in tiffPaths:
|
||||
async_results.append(
|
||||
pool.apply_async(preProcessTiFF, (tiffpath,preFolderPath,))
|
||||
)
|
||||
|
||||
for shppath in shpPaths:
|
||||
async_results.append(
|
||||
pool.apply_async(preProcessLabelshapefile, (shppath,preFolderPath,))
|
||||
)
|
||||
|
||||
# 条带模式
|
||||
srcFolderPath = r"D:\Annotation_Y\港口\条带模式"
|
||||
tiffPaths = find_tif_files_pathlib(srcFolderPath)
|
||||
shpPaths = find_shp_files_pathlib(srcFolderPath)
|
||||
preFolderPath = r"D:\Annotation_Y\预处理\条带模式"
|
||||
for tiffpath in tiffPaths:
|
||||
async_results.append(
|
||||
pool.apply_async(preProcessTiFF, (tiffpath,preFolderPath,))
|
||||
)
|
||||
|
||||
for shppath in shpPaths:
|
||||
async_results.append(
|
||||
pool.apply_async(preProcessLabelshapefile, (shppath,preFolderPath,))
|
||||
)
|
||||
|
||||
|
||||
for async_result in async_results:
|
||||
print(async_result.get())
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,112 @@
|
|||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
########################################################
|
||||
# 函数区
|
||||
########################################################
|
||||
|
||||
spacetySliceEnvPathExEPath=r"D:\ProgramData\miniconda3\envs\spacetySliceEnv\python.exe"
|
||||
|
||||
def find_tif_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.bin'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def find_txt_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.txt'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def matchTiff_Txt(tiffpaths,txtPaths):
|
||||
match_results={}
|
||||
tiffID=0
|
||||
for tid in range(len(tiffpaths)):
|
||||
tiffID=tiffID+1
|
||||
match_results[tiffID]={"tiff":tiffpaths[tid],"txt":[]}
|
||||
rootname=Path(tiffpaths[tid]).stem
|
||||
for txtpath in txtPaths:
|
||||
txtrootname=Path(txtpath).stem
|
||||
if txtrootname.startswith(rootname):
|
||||
match_results[tiffID]["txt"].append(txtpath)
|
||||
|
||||
return match_results
|
||||
|
||||
def sliceTiFFAndTxt(match_meta,outfolderpath):
|
||||
resultTxt=""
|
||||
programpath = r"R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\DataSampleSliceTrainDataset.py"
|
||||
tiffPath=match_meta["tiff"]
|
||||
for txtpath in match_meta["txt"]:
|
||||
cmdtxt = r"{} {} -i {} -l {} -o {}".format(spacetySliceEnvPathExEPath, programpath,
|
||||
tiffPath,
|
||||
txtpath,
|
||||
outfolderpath
|
||||
)
|
||||
|
||||
if os.system(cmdtxt) == 2:
|
||||
resultTxt="{}\nsucess: {}".format(resultTxt,txtpath)
|
||||
print("sucess:", cmdtxt)
|
||||
|
||||
else:
|
||||
resultTxt = "{}\nfailed: {}".format(resultTxt, txtpath)
|
||||
print("failed:", cmdtxt)
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
async_results = []
|
||||
with Pool() as pool:
|
||||
# 聚束模式
|
||||
preFolderPath = r"D:\Annotation_Y\预处理\聚束模式"
|
||||
outfolderPath=r"D:\Annotation_Y\切片样本\聚束模式"
|
||||
tiffPaths = find_tif_files_pathlib(preFolderPath)
|
||||
txtPaths = find_txt_files_pathlib(preFolderPath)
|
||||
match_results=matchTiff_Txt(tiffPaths,txtPaths)
|
||||
|
||||
for tiffID in match_results:
|
||||
match_meta=match_results[tiffID]
|
||||
async_results.append(
|
||||
pool.apply_async(sliceTiFFAndTxt, (match_meta,outfolderPath,))
|
||||
)
|
||||
|
||||
# 聚束模式
|
||||
preFolderPath = r"D:\Annotation_Y\预处理\条带模式"
|
||||
outfolderPath=r"D:\Annotation_Y\切片样本\条带模式"
|
||||
tiffPaths = find_tif_files_pathlib(preFolderPath)
|
||||
txtPaths = find_txt_files_pathlib(preFolderPath)
|
||||
match_results=matchTiff_Txt(tiffPaths,txtPaths)
|
||||
|
||||
for tiffID in match_results:
|
||||
match_meta=match_results[tiffID]
|
||||
async_results.append(
|
||||
pool.apply_async(sliceTiFFAndTxt, (match_meta,outfolderPath,))
|
||||
)
|
||||
|
||||
for async_result in async_results:
|
||||
print(async_result.get())
|
||||
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
import os
|
||||
import re
|
||||
# import pandas as pd
|
||||
import csv
|
||||
from collections import defaultdict
|
||||
import argparse
|
||||
|
||||
def stats_ship_labels(input_dir, output_file, person="", work_time=""):
|
||||
header = [
|
||||
"标签", "负责人", "作业时间",
|
||||
"军用飞机", "民用飞机", "军民一体飞机",
|
||||
"军用轮船", "民用轮船",
|
||||
"民用机场", "军用机场", "军民一体机场",
|
||||
"民用港口", "军用港口", "军民一体港口",
|
||||
"总计"
|
||||
]
|
||||
alias = [
|
||||
"SAR影像名", "StudentID", "work_time",
|
||||
"military_airplane", "civil_airplane", "mix_airplane",
|
||||
"military_ship", "civil_ship",
|
||||
"civil_airport", "military_airport", "mix_airport",
|
||||
"military_harbor", "civil_harbor", "mix_harbor",
|
||||
"Total"
|
||||
]
|
||||
|
||||
stats = defaultdict(int)
|
||||
|
||||
for fname in os.listdir(input_dir):
|
||||
if not fname.endswith(".txt"):
|
||||
continue
|
||||
|
||||
original_name = re.sub(r'_\d+_image\.txt', '', fname)
|
||||
file_path = os.path.join(input_dir, fname)
|
||||
|
||||
# with open(file_path, "r", encoding="utf-8") as f: # 统计的是
|
||||
# for line in f:
|
||||
# parts = line.strip().split()
|
||||
# if len(parts) < 9:
|
||||
# continue
|
||||
# cls = parts[-1]
|
||||
# if cls == "ship":
|
||||
# stats[original_name]["民用轮船"] += 1
|
||||
|
||||
stats[original_name] += 1 # 统计的是有ship的切片数量
|
||||
|
||||
# rows = []
|
||||
# for original_name, counts in stats.items():
|
||||
# row = {
|
||||
# "标签":original_name,
|
||||
# "负责人":person,
|
||||
# "作业时间":work_time,
|
||||
# "民用飞机":0,
|
||||
# "军用飞机":0,
|
||||
# "军民一体飞机":0,
|
||||
# "军用轮船":0,
|
||||
# "民用轮船":counts["民用轮船"],
|
||||
# "民用机场":0,
|
||||
# "军用机场":0,
|
||||
# "军民一体机场":0,
|
||||
# "军用港口":0,
|
||||
# "民用港口":0,
|
||||
# "军民一体港口":0
|
||||
# }
|
||||
# row["总计"] = row["民用轮船"]
|
||||
# rows.append(row)
|
||||
#
|
||||
# df = pd.DataFrame(rows)
|
||||
#
|
||||
# alias_df = pd.DataFrame([dict(zip(header, alias))])
|
||||
# df = pd.concat([alias_df, df], ignore_index=True)
|
||||
#
|
||||
# total_row = {col:0 for col in header}
|
||||
# total_row["标签"] = ""
|
||||
# total_row["负责人"] = ""
|
||||
# total_row["作业时间"] = ""
|
||||
# for col in header[3:]:
|
||||
# total_row[col] = df[col][1:].astype(int).sum()
|
||||
# df.loc[len(df)] = total_row
|
||||
#
|
||||
# df.to_csv(output_file, index=False)
|
||||
# print(f"统计完成,结果保存到 {output_file}")
|
||||
|
||||
with open(output_file,"w", newline="",encoding="utf-8") as f:
|
||||
writer = csv.writer(f, delimiter=',')
|
||||
writer.writerow(header)
|
||||
writer.writerow(alias)
|
||||
|
||||
total_counts = [0] * (len(header) - 3)
|
||||
|
||||
for original_name, ship_count in stats.items():
|
||||
row = [original_name, person, work_time] + [0,0,0,0,ship_count,0,0,0,0,0,0]
|
||||
total = ship_count
|
||||
row.append(total)
|
||||
|
||||
for i, val in enumerate(row[3:], start=0):
|
||||
total_counts[i] += val
|
||||
|
||||
writer.writerow(row)
|
||||
total_row = ["","",""] + total_counts
|
||||
writer.writerow(total_row)
|
||||
print(f"统计完成,结果保存到{output_file}")
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inlabelfolder',type=str,default=r'R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\剔除空标注\G6',
|
||||
help='输入tiff的bin文件')
|
||||
parser.add_argument('-o', '--outcsvpath',type=str,default=r'D:\TYSAR-德清院\切片工作统计表_0818G6.csv',
|
||||
help='切片文件夹地址')
|
||||
parser.add_argument('-p', '--person', type=str, default=f"",
|
||||
help='切片文件夹地址')
|
||||
parser.add_argument('-w', '--work_time', type=str, default=f"",
|
||||
help='切片文件夹地址')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = getParams()
|
||||
inlabelfolder = args.inlabelfolder
|
||||
outcsvpath = args.outcsvpath
|
||||
person = args.person
|
||||
work_time = args.work_time
|
||||
print('inlabelfolder:', inlabelfolder)
|
||||
print('outcsvpath:', outcsvpath)
|
||||
stats_ship_labels(inlabelfolder,outcsvpath, person, work_time)
|
||||
|
|
@ -0,0 +1,43 @@
|
|||
import os
|
||||
import re
|
||||
import shutil
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
|
||||
def copy_one(tiff_path, target_path):
|
||||
shutil.copy(tiff_path, target_path)
|
||||
return os.path.basename(tiff_path)
|
||||
|
||||
def copy_file_by_txt(txt_path, tiff_path, dst_path, workers=8):
|
||||
os.makedirs(dst_path, exist_ok=True)
|
||||
|
||||
# 遍历所有txt
|
||||
tiff_files = {re.sub(r'_image.tiff', '', f): f for f in os.listdir(tiff_path) if f.lower().endswith('.tiff')}
|
||||
|
||||
tasks = []
|
||||
with ThreadPoolExecutor(max_workers=workers) as executor:
|
||||
# 遍历txt_path中所有txt
|
||||
for file in os.listdir(txt_path):
|
||||
if file.lower().endswith('.txt'):
|
||||
# basename = os.path.splitext(file)[0]
|
||||
basename = re.sub(r'_image.txt', '', file)
|
||||
if basename in tiff_files:
|
||||
tiff_name = tiff_files[basename]
|
||||
tiff_folder = os.path.join(tiff_path, tiff_name)
|
||||
target_folder = os.path.join(dst_path, tiff_name)
|
||||
|
||||
# 并发提交复制任务
|
||||
tasks.append(executor.submit(copy_one, tiff_folder, target_folder))
|
||||
|
||||
for future in as_completed(tasks):
|
||||
try:
|
||||
print(f"Copied: {future.result()}")
|
||||
except Exception as e:
|
||||
print(f"Error copying file: {e}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
txt_path = r"R:\TYSAR-德清院\B-模型处理-预标注\20250826-不分类-处理20250906\人工检查\剔除空标注\20250918"
|
||||
tiff_path = r"R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250826-不分类\A-预处理\AB-图像预处理\tifffolder"
|
||||
dst_path = r"R:\TYSAR-德清院\B-模型处理-预标注\20250826-不分类-处理20250906\人工检查\剔除空标注\20250918"
|
||||
|
||||
copy_file_by_txt(txt_path, tiff_path, dst_path)
|
||||
|
|
@ -0,0 +1,84 @@
|
|||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240827t214056-009683-0025d3-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241122t080831-012900-003264-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240819t021822-009420-0024cc-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240910t021759-010207-0027df-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241219t033708-013921-003661-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240910t021831-010207-0027df-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241103t111113-012211-002fb3-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241218t021646-013863-003627-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241101t084234-012136-002f68-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241108t135950-012395-00306b-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241215t122646-013772-0035cc-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241215t122648-013772-0035cc-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241226t122634-014261-0037b5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241115t021646-012620-00314c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241216t034702-013800-0035e8-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241218t021642-013863-003627-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240817t202714-009398-0024b6-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241021t021904-011733-002dd5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241023t111125-011817-002e29-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241112t122724-012536-0030f8-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240827t122843-009664-0025c0-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241101t105535-012138-002f6a-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241123t105515-012941-00328d-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241103t210548-012228-002fc4-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241114t130618-012600-003138-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240921t021815-010631-002987-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240828t153541-009717-0025f5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240815t122523-009325-00246d-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240827t105651-009663-0025bf-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241127t225015-013116-00333c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240920t210636-010626-002982-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241117t013907-012689-003191-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240918t122824-010544-002930-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241010t021916-011334-002c46-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240922t225127-010709-0029d5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241112t213940-012552-003108-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240829t130742-009742-00260e-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240918t214040-010561-002941-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241215t021804-013749-0035b5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241111t080843-012502-0030d6-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241126t021713-013049-0032f9-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241101t105539-012138-002f6a-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240827t084346-009662-0025be-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241024t021710-011832-002e38-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240930t153505-011015-002b07-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240907t122836-010072-002758-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241110t020441-012455-0030a7-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241115t021715-012620-00314c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241217t102028-013843-003613-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240826t152806-009646-0025ae-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241130t135926-013209-003399-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240910t021838-010207-0027df-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241215t213903-013785-0035d9-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240919t034839-010575-00294f-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241011t202614-011404-002c8c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240906t152754-010057-002749-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240905t020553-009990-002706-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241103t130630-012213-002fb5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241024t021749-011832-002e38-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241014t033821-011481-002cd9-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241023t102128-011816-002e28-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241123t021828-012924-00327c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240814t020617-009277-00243d-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241204t122654-013349-003425-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240819t021851-009420-0024cc-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241115t021726-012620-00314c-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241121t020429-012848-003230-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241214t152605-013721-003599-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241226t122636-014261-0037b5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241102t202550-012196-002fa4-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241102t034750-012167-002f87-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240918t084323-010542-00292e-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240921t021822-010631-002987-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240825t020605-009602-002582-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241204t105503-013348-003424-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241208t225002-013530-0034da-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240816t122900-009362-002492-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241204t105459-013348-003424-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241103t130626-012213-002fb5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20240817t153553-009392-0024b0-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241112t084222-012534-0030f6-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241215t021815-013749-0035b5-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241001t130702-011042-002b22-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
d:\ProgramData\anaconda3\envs\spacetySliceEnv\python.exe "R:\TYSAR-德清院\A-预处理-未标注\A0-算法版本\AA\SpacetySliceDataTools\tools\SpacetyTIFFDataStretch2PNG_AB.py" -i "R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\0-原图\Geo_bc3-sm-org-vv-20241204t122658-013349-003425-01.tiff" -o "D:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250903-不分类\A-预处理\AB-图像预处理" --slicemode --SquareRoot
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -0,0 +1,551 @@
|
|||
import os
|
||||
import argparse
|
||||
from osgeo import ogr,gdal
|
||||
from matplotlib import pyplot as plt
|
||||
from osgeo import gdal
|
||||
import matplotlib
|
||||
import matplotlib.patches as patches
|
||||
from osgeo import gdal
|
||||
from PIL import Image
|
||||
from scipy.spatial import cKDTree
|
||||
import numpy as np
|
||||
from DotaOperator import DotaObj,createDota,readDotaFile,writerDotaFile
|
||||
import argparse
|
||||
import math
|
||||
from math import ceil, floor
|
||||
##########################################################################
|
||||
# 函数区
|
||||
##########################################################################
|
||||
def read_tif(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans, im_data
|
||||
|
||||
|
||||
def Strech_SquareRoot(im_data):
|
||||
# 判断是否为dB
|
||||
# immask = np.isfinite(im_data)
|
||||
# imvail_data = im_data[immask]
|
||||
# minvalue = np.percentile(imvail_data,30)
|
||||
# if minvalue<0 :
|
||||
# im_data=np.power(10.0,im_data/10.0)
|
||||
|
||||
im_data=np.sqrt(im_data)
|
||||
immask = np.isfinite(im_data)
|
||||
imvail_data = im_data[immask]
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
minvalue_01Prec = np.percentile(imvail_data, 0.1) # 20250904 1%拉伸
|
||||
maxvalue_999Prec = np.percentile(imvail_data, 99.9)
|
||||
print('sqrt root min - max ', minvalue,maxvalue)
|
||||
if (maxvalue-minvalue)/(maxvalue_999Prec-minvalue_01Prec)>3: # 表示 拉伸之后,像素值绝大部分很有可能集中在 80
|
||||
minvalue=minvalue_01Prec
|
||||
maxvalue=maxvalue_999Prec
|
||||
print('sqrt root min(0.1) - max(99.9) ', minvalue, maxvalue)
|
||||
|
||||
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def write_envi(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Float32)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
outfilepath=output_path.replace(".tiff",".png")
|
||||
im_data_uint8=Strech_SquareRoot(im_data)
|
||||
Image.fromarray(im_data_uint8).save(outfilepath, compress_level=0)
|
||||
|
||||
def geoXY2pixelXY(geo_x, geo_y, inv_gt):
|
||||
pixel_x = inv_gt[0] + geo_x * inv_gt[1] + geo_y * inv_gt[2]
|
||||
pixel_y = inv_gt[3] + geo_x * inv_gt[4] + geo_y * inv_gt[5]
|
||||
return pixel_x, pixel_y
|
||||
|
||||
def label2pixelpoints(dotapath,tiff_inv_trans,methodstr,filterlabels):
|
||||
dotalist = readDotaFile(dotapath,filterlabels)
|
||||
if methodstr=="geolabel":
|
||||
for i in range(len(dotalist)):
|
||||
geo_x = dotalist[i].x1 # x1
|
||||
geo_y = dotalist[i].y1
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x1 = pixel_x
|
||||
dotalist[i].y1 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x2 # x2
|
||||
geo_y = dotalist[i].y2
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x2 = pixel_x
|
||||
dotalist[i].y2 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x3 # x3
|
||||
geo_y = dotalist[i].y3
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x3 = pixel_x
|
||||
dotalist[i].y3 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x4 # x4
|
||||
geo_y = dotalist[i].y4
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x4 = pixel_x
|
||||
dotalist[i].y4 = pixel_y
|
||||
|
||||
print("点数:", len(dotalist))
|
||||
return dotalist
|
||||
|
||||
def getMaxEdge(dotalist, ids):
|
||||
cornpoint = np.zeros((len(ids) * 4, 2))
|
||||
for idx in range(len(ids)):
|
||||
cornpoint[idx * 4 + 0, 0] = dotalist[ids[idx]].x1
|
||||
cornpoint[idx * 4 + 1, 0] = dotalist[ids[idx]].x2
|
||||
cornpoint[idx * 4 + 2, 0] = dotalist[ids[idx]].x3
|
||||
cornpoint[idx * 4 + 3, 0] = dotalist[ids[idx]].x4
|
||||
|
||||
cornpoint[idx * 4 + 0, 1] = dotalist[ids[idx]].y1
|
||||
cornpoint[idx * 4 + 1, 1] = dotalist[ids[idx]].y2
|
||||
cornpoint[idx * 4 + 2, 1] = dotalist[ids[idx]].y3
|
||||
cornpoint[idx * 4 + 3, 1] = dotalist[ids[idx]].y4
|
||||
|
||||
xedge = np.max(cornpoint[:, 0]) - np.min(cornpoint[:, 0])
|
||||
yedge = np.max(cornpoint[:, 1]) - np.min(cornpoint[:, 1])
|
||||
|
||||
edgelen = xedge if xedge > yedge else yedge
|
||||
return edgelen
|
||||
|
||||
def getExternCenter(dotalist, ids):
|
||||
cornpoint = np.zeros((len(ids) * 4, 2))
|
||||
for idx in range(len(ids)):
|
||||
cornpoint[idx * 4 + 0, 0] = dotalist[ids[idx]].x1
|
||||
cornpoint[idx * 4 + 1, 0] = dotalist[ids[idx]].x2
|
||||
cornpoint[idx * 4 + 2, 0] = dotalist[ids[idx]].x3
|
||||
cornpoint[idx * 4 + 3, 0] = dotalist[ids[idx]].x4
|
||||
|
||||
cornpoint[idx * 4 + 0, 1] = dotalist[ids[idx]].y1
|
||||
cornpoint[idx * 4 + 1, 1] = dotalist[ids[idx]].y2
|
||||
cornpoint[idx * 4 + 2, 1] = dotalist[ids[idx]].y3
|
||||
cornpoint[idx * 4 + 3, 1] = dotalist[ids[idx]].y4
|
||||
|
||||
minX = np.min(cornpoint[:, 0])
|
||||
minY = np.min(cornpoint[:, 1])
|
||||
maxX = np.max(cornpoint[:, 0])
|
||||
maxY = np.max(cornpoint[:, 1])
|
||||
centerX = (minX + maxX) / 2
|
||||
centerY = (minY + maxY) / 2
|
||||
return [centerX, centerY, minX, minY, maxX, maxY]
|
||||
|
||||
def drawSliceRasterPrivew(tiff_data,dotalist,clusterDict):
|
||||
# 绘制图形
|
||||
# 创建图形和坐标轴
|
||||
fig, ax = plt.subplots(figsize=(20, 16))
|
||||
ax.imshow(tiff_data, cmap='gray')
|
||||
# 绘制每个目标的矩形框并标注坐标
|
||||
for i in range(len(dotalist)):
|
||||
# 提取x和y坐标
|
||||
x_coords = [dotalist[i].x1, dotalist[i].x2, dotalist[i].x3, dotalist[i].x4]
|
||||
y_coords = [dotalist[i].y1, dotalist[i].y2, dotalist[i].y3, dotalist[i].y4]
|
||||
|
||||
# 计算最小外接矩形(AABB)
|
||||
x_min, x_max = min(x_coords), max(x_coords)
|
||||
y_min, y_max = min(y_coords), max(y_coords)
|
||||
width = x_max - x_min
|
||||
height = y_max - y_min
|
||||
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
rect = patches.Rectangle(
|
||||
(x_min, y_min), width, height,
|
||||
linewidth=2, edgecolor='red', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
|
||||
# ax.annotate(f'({x},{y})', xy=(x, y), xytext=(5, 5),
|
||||
# textcoords='offset points', fontsize=10,
|
||||
# bbox=dict(boxstyle='round,pad=0.5', fc='white', alpha=0.8))
|
||||
|
||||
# 在矩形中心标注目标编号
|
||||
center_x = sum(x_coords) / 4
|
||||
center_y = sum(y_coords) / 4
|
||||
ax.text(center_x, center_y, str(i),
|
||||
ha='center', va='center', fontsize=6, color='red')
|
||||
|
||||
# 以类别中心为中心绘制四边形
|
||||
for k in clusterDict:
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
minX = clusterDict[k]["p"][0]
|
||||
minY = clusterDict[k]["p"][1]
|
||||
rect = patches.Rectangle(
|
||||
(minX , minY), 1024, 1024,
|
||||
linewidth=2, edgecolor='green', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
ax.text(minX+512, minY+512, str(k),
|
||||
ha='center', va='center', fontsize=6, color='green')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
print("绘图结束")
|
||||
return None
|
||||
|
||||
def find_optimal_slices(H, W, boxes, patch_size=1024, max_overlap_rate=0.2):
|
||||
"""
|
||||
Compute optimal slice positions for the image to maximize the number of fully contained rectangular patches (boxes),
|
||||
while ensuring the overlap rate between any two slices does not exceed the specified maximum.
|
||||
|
||||
Parameters:
|
||||
- H: Height of the image.
|
||||
- W: Width of the image.
|
||||
- boxes: List of tuples or lists, each containing (x1, y1, x2, y2) where (x1, y1) is the top-left and (x2, y2) is the bottom-right of a rectangular patch.
|
||||
- patch_size: Size of each slice (square, e.g., 1024).
|
||||
- max_overlap_rate: Maximum allowed overlap rate (e.g., 0.2).
|
||||
|
||||
Returns:
|
||||
- slices: List of (sx, sy) starting positions for the slices.
|
||||
- covered_count: Number of patches that appear fully in at least one slice.
|
||||
"""
|
||||
overlap_max = patch_size * max_overlap_rate
|
||||
stride = patch_size - floor(overlap_max) # Ensures overlap <= max_overlap_rate in linear dimensions
|
||||
|
||||
N = len(boxes)
|
||||
x_covered = [set() for _ in range(stride)]
|
||||
y_covered = [set() for _ in range(stride)]
|
||||
|
||||
for i in range(N):
|
||||
x1, y1, x2, y2 = boxes[i]
|
||||
b_w = x2 - x1
|
||||
b_h = y2 - y1
|
||||
|
||||
# For x-dimension
|
||||
lx = max(0, x2 - patch_size)
|
||||
rx = min(W - patch_size, x1)
|
||||
if lx <= rx:
|
||||
start_x = ceil(lx)
|
||||
end_x = floor(rx)
|
||||
l_x = end_x - start_x + 1
|
||||
if l_x > 0:
|
||||
if l_x >= stride:
|
||||
for ox in range(stride):
|
||||
x_covered[ox].add(i)
|
||||
else:
|
||||
for sx in range(start_x, end_x + 1):
|
||||
ox = sx % stride
|
||||
x_covered[ox].add(i)
|
||||
|
||||
# For y-dimension
|
||||
ly = max(0, y2 - patch_size)
|
||||
ry = min(H - patch_size, y1)
|
||||
if ly <= ry:
|
||||
start_y = ceil(ly)
|
||||
end_y = floor(ry)
|
||||
l_y = end_y - start_y + 1
|
||||
if l_y > 0:
|
||||
if l_y >= stride:
|
||||
for oy in range(stride):
|
||||
y_covered[oy].add(i)
|
||||
else:
|
||||
for sy in range(start_y, end_y + 1):
|
||||
oy = sy % stride
|
||||
y_covered[oy].add(i)
|
||||
|
||||
# Find the best offset pair (ox, oy) that maximizes covered patches
|
||||
max_covered = 0
|
||||
best_ox = 0
|
||||
best_oy = 0
|
||||
for ox in range(stride):
|
||||
for oy in range(stride):
|
||||
current_covered = len(x_covered[ox] & y_covered[oy])
|
||||
if current_covered > max_covered:
|
||||
max_covered = current_covered
|
||||
best_ox = ox
|
||||
best_oy = oy
|
||||
|
||||
# Generate the slice positions using the best offsets and stride
|
||||
slices = []
|
||||
sx = best_ox
|
||||
while sx + patch_size <= W:
|
||||
sy = best_oy
|
||||
while sy + patch_size <= H:
|
||||
slices.append((sx, sy))
|
||||
sy += stride
|
||||
sx += stride
|
||||
|
||||
return slices, max_covered
|
||||
|
||||
def check_B_in_A(A,B):
|
||||
"""
|
||||
判断A包含B
|
||||
:param A: [x0,y0.w.h]
|
||||
:param B: [x0,y0.w.h]
|
||||
:return:
|
||||
"""
|
||||
# 解构矩形A和B的参数
|
||||
Ax0, Ay0, Aw, Ah = A
|
||||
Bx0, By0, Bw, Bh = B
|
||||
|
||||
# 计算矩形A和B的右边界和下边界
|
||||
Ax1 = Ax0 + Aw
|
||||
Ay1 = Ay0 + Ah
|
||||
Bx1 = Bx0 + Bw
|
||||
By1 = By0 + Bh
|
||||
|
||||
# 判断B是否完全在A内部
|
||||
return (Bx0 >= Ax0) and (Bx1 <= Ax1) and (By0 >= Ay0) and (By1 <= Ay1)
|
||||
|
||||
|
||||
##########################################################################
|
||||
# 切分算法流程图
|
||||
##########################################################################
|
||||
|
||||
def getclusterDict(dotalist,imgheight,imgwidth,pitchSize=1024,max_overlap_rate=0.2):
|
||||
"""
|
||||
生成切片数据
|
||||
:param dotalist: 样本集
|
||||
:param imgheight: 图像高度
|
||||
:param imgwidth: 图像宽度
|
||||
:return: 切片类型
|
||||
"""
|
||||
boxs=[]
|
||||
for i in range(len(dotalist)):
|
||||
xs=np.array([dotalist[i].x1,dotalist[i].x2,dotalist[i].x3, dotalist[i].x4])
|
||||
ys=np.array([dotalist[i].y1,dotalist[i].y2,dotalist[i].y3, dotalist[i].y4])
|
||||
x1=np.min(xs)
|
||||
x2=np.max(xs)
|
||||
y1=np.min(ys)
|
||||
y2=np.max(ys)
|
||||
boxs.append([x1,y1,x2,y2]) # x1, y1, x2, y2 = boxes[i]
|
||||
|
||||
slices, max_covered=find_optimal_slices(imgheight,imgwidth,boxs,pitchSize,max_overlap_rate)
|
||||
|
||||
clusterDict={}
|
||||
|
||||
waitContaindota=[]
|
||||
hasContainIds=[]
|
||||
for i in range(len(slices)):
|
||||
sx,sy=slices[i]
|
||||
clusterDict[i]={"p":[sx,sy],"id":[]}
|
||||
slicesExten=[sx,sy,1024,1024]
|
||||
for ids in range(len(dotalist)):
|
||||
if ids in hasContainIds:
|
||||
continue
|
||||
else:
|
||||
[centerX, centerY, minX, minY, maxX, maxY]=getExternCenter(dotalist, [ids])
|
||||
dotaExtend=[minX,minY,maxX-minX,maxY-minY]
|
||||
if check_B_in_A(slicesExten,dotaExtend):
|
||||
clusterDict[i]["id"].append(ids)
|
||||
hasContainIds.append(ids)
|
||||
|
||||
for ids in range(len(dotalist)):
|
||||
if ids in hasContainIds:
|
||||
continue
|
||||
else:
|
||||
waitContaindota.append(ids)
|
||||
print("No in slice dota : ",str(dotalist[ids]) )
|
||||
|
||||
print("no process ids ",str(waitContaindota))
|
||||
return clusterDict
|
||||
|
||||
|
||||
def drawSlictplot(clusterDict,dotalist,tiff_data,nrows=10,ncols=9):
|
||||
"""
|
||||
:param clusterDict: clusterDict[i]={"p":[sx,sy],"id":[]}
|
||||
:param dotalist: (x1, y1, x2, y2, x3, y3, x4, y4 clsname diffcule)
|
||||
:return:
|
||||
"""
|
||||
fig, axes = plt.subplots(nrows=nrows,ncols=ncols,figsize=(20, 16))
|
||||
plt.tight_layout(pad=3.0)
|
||||
|
||||
# 9*10
|
||||
subid=0
|
||||
for cid in clusterDict:
|
||||
sx,sy=clusterDict[cid]["p"]
|
||||
colid=subid//nrows
|
||||
rowid=subid%nrows
|
||||
subid=subid+1
|
||||
ax = axes[rowid, colid]
|
||||
ax.set_title(str(cid))
|
||||
sliceData=tiff_data[sy:(sy+1024),sx:(sx+1024)]
|
||||
ax.imshow(sliceData, cmap='gray')
|
||||
|
||||
for did in clusterDict[cid]["id"] :
|
||||
# 提取x和y坐标
|
||||
x_coords = [dotalist[did].x1-sx, dotalist[did].x2-sx, dotalist[did].x3-sx, dotalist[did].x4-sx]
|
||||
y_coords = [dotalist[did].y1-sy, dotalist[did].y2-sy, dotalist[did].y3-sy, dotalist[did].y4-sy]
|
||||
|
||||
# 计算最小外接矩形(AABB)
|
||||
x_min, x_max = min(x_coords), max(x_coords)
|
||||
y_min, y_max = min(y_coords), max(y_coords)
|
||||
width = x_max - x_min
|
||||
height = y_max - y_min
|
||||
|
||||
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
rect = patches.Rectangle(
|
||||
(x_min, y_min), width, height,
|
||||
linewidth=2, edgecolor='red', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
|
||||
# 在矩形中心标注目标编号
|
||||
center_x = x_min+width/2
|
||||
center_y = y_min+height/2
|
||||
ax.text(center_x, center_y, str(did),
|
||||
ha='center', va='center', fontsize=6, color='red')
|
||||
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
print("绘图结束")
|
||||
return None
|
||||
|
||||
|
||||
def slictDataAndOutlabel(clusterDict,dotalist,tiff_data,tiff_basename,outfolderpath,im_geotrans, im_proj):
|
||||
"""
|
||||
切分标签,输出结果与文件
|
||||
:param clusterDict:
|
||||
:param dotalist:
|
||||
:param tiff_data:
|
||||
:param tiff_name:
|
||||
:param outfolderpath:
|
||||
:return:
|
||||
"""
|
||||
for cid in clusterDict:
|
||||
sx, sy = clusterDict[cid]["p"]
|
||||
if len(clusterDict[cid]["id"])==0:
|
||||
continue
|
||||
sliceData = tiff_data[sy:(sy + 1024), sx:(sx + 1024)]
|
||||
outbinname="{}_{}.tiff".format(tiff_basename,cid)
|
||||
outlabelname="{}_{}.txt".format(tiff_basename,cid)
|
||||
# 获取样本列表
|
||||
outdotalist=[]
|
||||
for did in clusterDict[cid]["id"] :
|
||||
x1=dotalist[did].x1-sx
|
||||
x2=dotalist[did].x2-sx
|
||||
x3=dotalist[did].x3-sx
|
||||
x4=dotalist[did].x4-sx
|
||||
y1=dotalist[did].y1-sy
|
||||
y2=dotalist[did].y2-sy
|
||||
y3=dotalist[did].y3-sy
|
||||
y4=dotalist[did].y4-sy
|
||||
tempdota=createDota(x1,y1,x2,y2,x3,y3,x4,y4,dotalist[did].clsname,dotalist[did].difficulty)
|
||||
outdotalist.append(tempdota)
|
||||
|
||||
outlabelpath=os.path.join(outfolderpath,outlabelname)
|
||||
outbinpath=os.path.join(outfolderpath,outbinname)
|
||||
|
||||
temp_im_geotrans=[tempi for tempi in im_geotrans]
|
||||
# 处理 0,3
|
||||
temp_im_geotrans[0]=im_geotrans[0]+sx*im_geotrans[1]+im_geotrans[2]*sy # x
|
||||
temp_im_geotrans[3]=im_geotrans[3]+sx*im_geotrans[4]+im_geotrans[5]*sy # y
|
||||
write_envi(sliceData,temp_im_geotrans,im_proj,outbinpath)
|
||||
writerDotaFile(outdotalist,outlabelpath)
|
||||
|
||||
##########################################################################
|
||||
# 处理流程图
|
||||
##########################################################################
|
||||
def DataSampleSliceRasterProcess(inbinfile,labelfilepath,outfolderpath,methodstr,filterlabels):
|
||||
tiff_proj, tiff_trans, tiff_data = read_tif(inbinfile)
|
||||
tiff_inv_trans = gdal.InvGeoTransform(tiff_trans)
|
||||
dotalist=label2pixelpoints(labelfilepath,tiff_inv_trans,methodstr,filterlabels)
|
||||
imgheight, imgwidth=tiff_data.shape
|
||||
clusterDict=getclusterDict(dotalist,imgheight,imgwidth)
|
||||
# drawSliceRasterPrivew(tiff_data, dotalist, clusterDict)
|
||||
ncols=int(len(clusterDict)/9+1)
|
||||
# drawSlictplot(clusterDict, dotalist, tiff_data, 9, ncols)
|
||||
tiff_name=os.path.basename(inbinfile)
|
||||
tiff_basename=os.path.splitext(tiff_name)[0]
|
||||
slictDataAndOutlabel(clusterDict, dotalist, tiff_data, tiff_basename, outfolderpath, tiff_trans, tiff_proj)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inbinfile',type=str,default=r'D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01.tiff', help='输入tiff的bin文件')
|
||||
parser.add_argument('-l', '--labelfilepath',type=str,default=r"D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01_LC.txt", help='输入标注')
|
||||
parser.add_argument('-o', '--outfolderpath',type=str,default=r'D:\Annotation_Y\切分', help='切片文件夹地址')
|
||||
parser.add_argument('-f', '--filterlabel',type=str,default=r'JLC;MLC', help='标签过滤')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--geolabel',
|
||||
action='store_const',
|
||||
const='geolabel',
|
||||
dest='method',
|
||||
help='标注坐标点为地理坐标'
|
||||
)
|
||||
group.add_argument(
|
||||
'--pixellabel',
|
||||
action='store_const',
|
||||
const='pixellabel',
|
||||
dest='method',
|
||||
help='标注坐标系统为输入影像的像空间坐标'
|
||||
)
|
||||
parser.set_defaults(method='geolabel')
|
||||
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
inbinfile=parser.inbinfile
|
||||
labelfilepath=parser.labelfilepath
|
||||
outfolderpath=parser.outfolderpath
|
||||
methodstr= parser.method
|
||||
filterlabels=parser.filterlabel.strip().split(';')
|
||||
print('inbinfile=',inbinfile)
|
||||
print('labelfilepath=',labelfilepath)
|
||||
print('outfolderpath=',outfolderpath)
|
||||
print('methodstr=',methodstr)
|
||||
print('filterlabels=',filterlabels)
|
||||
DataSampleSliceRasterProcess(inbinfile, labelfilepath, outfolderpath,methodstr,filterlabels)
|
||||
print("样本切分完成")
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,436 @@
|
|||
import os
|
||||
import argparse
|
||||
from osgeo import ogr,gdal
|
||||
from matplotlib import pyplot as plt
|
||||
from osgeo import gdal
|
||||
import matplotlib
|
||||
import matplotlib.patches as patches
|
||||
from osgeo import gdal
|
||||
from PIL import Image
|
||||
from scipy.spatial import cKDTree
|
||||
import numpy as np
|
||||
from DotaOperator import DotaObj,createDota,readDotaFile,writerDotaFile
|
||||
import argparse
|
||||
import math
|
||||
from math import ceil, floor
|
||||
import random
|
||||
|
||||
##########################################################################
|
||||
# 函数区
|
||||
##########################################################################
|
||||
def read_tif(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans, im_data
|
||||
|
||||
def write_envi(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("ENVI")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Byte)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
outfilepath=output_path.replace(".bin",".png")
|
||||
Image.fromarray(im_data).save(outfilepath, compress_level=0)
|
||||
|
||||
def geoXY2pixelXY(geo_x, geo_y, inv_gt):
|
||||
pixel_x = inv_gt[0] + geo_x * inv_gt[1] + geo_y * inv_gt[2]
|
||||
pixel_y = inv_gt[3] + geo_x * inv_gt[4] + geo_y * inv_gt[5]
|
||||
return pixel_x, pixel_y
|
||||
|
||||
def label2pixelpoints(dotapath,tiff_inv_trans,methodstr,filterlabels):
|
||||
dotalist = readDotaFile(dotapath,filterlabels)
|
||||
if methodstr=="geolabel":
|
||||
for i in range(len(dotalist)):
|
||||
geo_x = dotalist[i].x1 # x1
|
||||
geo_y = dotalist[i].y1
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x1 = pixel_x
|
||||
dotalist[i].y1 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x2 # x2
|
||||
geo_y = dotalist[i].y2
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x2 = pixel_x
|
||||
dotalist[i].y2 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x3 # x3
|
||||
geo_y = dotalist[i].y3
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x3 = pixel_x
|
||||
dotalist[i].y3 = pixel_y
|
||||
|
||||
geo_x = dotalist[i].x4 # x4
|
||||
geo_y = dotalist[i].y4
|
||||
pixel_x, pixel_y = geoXY2pixelXY(geo_x, geo_y, tiff_inv_trans)
|
||||
dotalist[i].x4 = pixel_x
|
||||
dotalist[i].y4 = pixel_y
|
||||
|
||||
print("点数:", len(dotalist))
|
||||
return dotalist
|
||||
|
||||
def getMaxEdge(dotalist, ids):
|
||||
cornpoint = np.zeros((len(ids) * 4, 2))
|
||||
for idx in range(len(ids)):
|
||||
cornpoint[idx * 4 + 0, 0] = dotalist[ids[idx]].x1
|
||||
cornpoint[idx * 4 + 1, 0] = dotalist[ids[idx]].x2
|
||||
cornpoint[idx * 4 + 2, 0] = dotalist[ids[idx]].x3
|
||||
cornpoint[idx * 4 + 3, 0] = dotalist[ids[idx]].x4
|
||||
|
||||
cornpoint[idx * 4 + 0, 1] = dotalist[ids[idx]].y1
|
||||
cornpoint[idx * 4 + 1, 1] = dotalist[ids[idx]].y2
|
||||
cornpoint[idx * 4 + 2, 1] = dotalist[ids[idx]].y3
|
||||
cornpoint[idx * 4 + 3, 1] = dotalist[ids[idx]].y4
|
||||
|
||||
xedge = np.max(cornpoint[:, 0]) - np.min(cornpoint[:, 0])
|
||||
yedge = np.max(cornpoint[:, 1]) - np.min(cornpoint[:, 1])
|
||||
|
||||
edgelen = xedge if xedge > yedge else yedge
|
||||
return edgelen
|
||||
|
||||
def getExternCenter(dotalist, ids):
|
||||
cornpoint = np.zeros((len(ids) * 4, 2))
|
||||
for idx in range(len(ids)):
|
||||
cornpoint[idx * 4 + 0, 0] = dotalist[ids[idx]].x1
|
||||
cornpoint[idx * 4 + 1, 0] = dotalist[ids[idx]].x2
|
||||
cornpoint[idx * 4 + 2, 0] = dotalist[ids[idx]].x3
|
||||
cornpoint[idx * 4 + 3, 0] = dotalist[ids[idx]].x4
|
||||
|
||||
cornpoint[idx * 4 + 0, 1] = dotalist[ids[idx]].y1
|
||||
cornpoint[idx * 4 + 1, 1] = dotalist[ids[idx]].y2
|
||||
cornpoint[idx * 4 + 2, 1] = dotalist[ids[idx]].y3
|
||||
cornpoint[idx * 4 + 3, 1] = dotalist[ids[idx]].y4
|
||||
|
||||
minX = np.min(cornpoint[:, 0])
|
||||
minY = np.min(cornpoint[:, 1])
|
||||
maxX = np.max(cornpoint[:, 0])
|
||||
maxY = np.max(cornpoint[:, 1])
|
||||
centerX = (minX + maxX) / 2
|
||||
centerY = (minY + maxY) / 2
|
||||
return [centerX, centerY, minX, minY, maxX, maxY]
|
||||
|
||||
def drawSliceRasterPrivew(tiff_data,dotalist,clusterDict):
|
||||
# 绘制图形
|
||||
# 创建图形和坐标轴
|
||||
fig, ax = plt.subplots(figsize=(20, 16))
|
||||
ax.imshow(tiff_data, cmap='gray')
|
||||
# 绘制每个目标的矩形框并标注坐标
|
||||
for i in range(len(dotalist)):
|
||||
# 提取x和y坐标
|
||||
x_coords = [dotalist[i].x1, dotalist[i].x2, dotalist[i].x3, dotalist[i].x4]
|
||||
y_coords = [dotalist[i].y1, dotalist[i].y2, dotalist[i].y3, dotalist[i].y4]
|
||||
|
||||
# 计算最小外接矩形(AABB)
|
||||
x_min, x_max = min(x_coords), max(x_coords)
|
||||
y_min, y_max = min(y_coords), max(y_coords)
|
||||
width = x_max - x_min
|
||||
height = y_max - y_min
|
||||
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
rect = patches.Rectangle(
|
||||
(x_min, y_min), width, height,
|
||||
linewidth=2, edgecolor='red', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
|
||||
# ax.annotate(f'({x},{y})', xy=(x, y), xytext=(5, 5),
|
||||
# textcoords='offset points', fontsize=10,
|
||||
# bbox=dict(boxstyle='round,pad=0.5', fc='white', alpha=0.8))
|
||||
|
||||
# 在矩形中心标注目标编号
|
||||
center_x = sum(x_coords) / 4
|
||||
center_y = sum(y_coords) / 4
|
||||
ax.text(center_x, center_y, str(i),
|
||||
ha='center', va='center', fontsize=6, color='red')
|
||||
|
||||
# 以类别中心为中心绘制四边形
|
||||
for k in clusterDict:
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
minX = clusterDict[k]["p"][0]
|
||||
minY = clusterDict[k]["p"][1]
|
||||
rect = patches.Rectangle(
|
||||
(minX , minY), 1024, 1024,
|
||||
linewidth=2, edgecolor='green', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
ax.text(minX+512, minY+512, str(k),
|
||||
ha='center', va='center', fontsize=6, color='green')
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
print("绘图结束")
|
||||
return None
|
||||
|
||||
|
||||
|
||||
def check_B_in_A(A,B):
|
||||
"""
|
||||
判断A包含B
|
||||
:param A: [x0,y0.w.h]
|
||||
:param B: [x0,y0.w.h]
|
||||
:return:
|
||||
"""
|
||||
# 解构矩形A和B的参数
|
||||
Ax0, Ay0, Aw, Ah = A
|
||||
Bx0, By0, Bw, Bh = B
|
||||
|
||||
# 计算矩形A和B的右边界和下边界
|
||||
Ax1 = Ax0 + Aw
|
||||
Ay1 = Ay0 + Ah
|
||||
Bx1 = Bx0 + Bw
|
||||
By1 = By0 + Bh
|
||||
|
||||
# 判断B是否完全在A内部
|
||||
return (Bx0 >= Ax0) and (Bx1 <= Ax1) and (By0 >= Ay0) and (By1 <= Ay1)
|
||||
|
||||
|
||||
##########################################################################
|
||||
# 切分算法流程图
|
||||
##########################################################################
|
||||
|
||||
def getclusterDict(dotalist,imgheight,imgwidth,pitchSize=1024,max_overlap_rate=0.2):
|
||||
"""
|
||||
生成切片数据
|
||||
:param dotalist: 样本集
|
||||
:param imgheight: 图像高度
|
||||
:param imgwidth: 图像宽度
|
||||
:return: 切片类型
|
||||
"""
|
||||
clusterDict = {} # clusterDict[i]={"p":[sx,sy],"id":[]}
|
||||
for did in range(len(dotalist)):
|
||||
centerX, centerY, minX, minY, maxX, maxY=getExternCenter(dotalist, [did])
|
||||
# 构建随机平移
|
||||
EdgeX=maxX-minX
|
||||
EdgeY=maxY-minY
|
||||
random_numX = random.random()*2-1
|
||||
random_numY = random.random()*2-1
|
||||
|
||||
offsetX=int(math.floor((pitchSize/2-EdgeX)*random_numX)) if pitchSize/2 > EdgeX else 0
|
||||
offsetY=int(math.floor((pitchSize/2-EdgeY)*random_numY)) if pitchSize/2 > EdgeY else 0
|
||||
|
||||
offsetX= offsetX if centerX+offsetX+pitchSize/2 < imgwidth else math.ceil(imgwidth-pitchSize/2-centerX-1)
|
||||
offsetY= offsetY if centerY+offsetY+pitchSize/2 < imgheight else math.ceil(imgheight-pitchSize/2-centerY-1)
|
||||
|
||||
offsetX= math.floor(pitchSize/2-centerX) if centerX+offsetX-pitchSize/2 < 0 else offsetX
|
||||
offsetY= math.floor(pitchSize/2-centerY) if centerY+offsetY-pitchSize/2 < 0 else offsetY
|
||||
|
||||
minX=int(centerX+offsetX-pitchSize/2)
|
||||
maxY=int(centerY+offsetY-pitchSize/2)
|
||||
|
||||
clusterDict[did]={"p":[minX,maxY],
|
||||
"id":[did]}
|
||||
|
||||
for cid in clusterDict:
|
||||
[minX,minY]=clusterDict[cid]["p"]
|
||||
Abox=[minX,minY,pitchSize,pitchSize]
|
||||
for did in range(len(dotalist)):
|
||||
[centerX, centerY, minX, minY, maxX, maxY] = getExternCenter(dotalist, [did])
|
||||
EdgeX = maxX - minX
|
||||
EdgeY = maxY - minY
|
||||
Bbox=[minX, minY,EdgeX,EdgeY]
|
||||
|
||||
if check_B_in_A(Abox,Bbox):
|
||||
if did not in clusterDict[cid]["id"]:
|
||||
clusterDict[cid]["id"].append(did)
|
||||
|
||||
return clusterDict
|
||||
|
||||
|
||||
def drawSlictplot(clusterDict,dotalist,tiff_data,nrows=10,ncols=9):
|
||||
"""
|
||||
:param clusterDict: clusterDict[i]={"p":[sx,sy],"id":[]}
|
||||
:param dotalist: (x1, y1, x2, y2, x3, y3, x4, y4 clsname diffcule)
|
||||
:return:
|
||||
"""
|
||||
fig, axes = plt.subplots(nrows=nrows,ncols=ncols,figsize=(20, 16))
|
||||
plt.tight_layout(pad=3.0)
|
||||
|
||||
# 9*10
|
||||
subid=0
|
||||
for cid in clusterDict:
|
||||
sx,sy=clusterDict[cid]["p"]
|
||||
colid=subid//nrows
|
||||
rowid=subid%nrows
|
||||
subid=subid+1
|
||||
ax = axes[rowid, colid]
|
||||
ax.set_title(str(cid))
|
||||
sliceData=tiff_data[sy:(sy+1024),sx:(sx+1024)]
|
||||
ax.imshow(sliceData, cmap='gray')
|
||||
|
||||
for did in clusterDict[cid]["id"] :
|
||||
# 提取x和y坐标
|
||||
x_coords = [dotalist[did].x1-sx, dotalist[did].x2-sx, dotalist[did].x3-sx, dotalist[did].x4-sx]
|
||||
y_coords = [dotalist[did].y1-sy, dotalist[did].y2-sy, dotalist[did].y3-sy, dotalist[did].y4-sy]
|
||||
|
||||
# 计算最小外接矩形(AABB)
|
||||
x_min, x_max = min(x_coords), max(x_coords)
|
||||
y_min, y_max = min(y_coords), max(y_coords)
|
||||
width = x_max - x_min
|
||||
height = y_max - y_min
|
||||
|
||||
|
||||
# 绘制无填充矩形框(仅红色边框)
|
||||
rect = patches.Rectangle(
|
||||
(x_min, y_min), width, height,
|
||||
linewidth=2, edgecolor='red', facecolor='none' # 关键:facecolor='none'
|
||||
)
|
||||
ax.add_patch(rect)
|
||||
|
||||
# 在矩形中心标注目标编号
|
||||
center_x = x_min+width/2
|
||||
center_y = y_min+height/2
|
||||
ax.text(center_x, center_y, str(did),
|
||||
ha='center', va='center', fontsize=6, color='red')
|
||||
|
||||
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
print("绘图结束")
|
||||
return None
|
||||
|
||||
|
||||
def slictDataAndOutlabel(clusterDict,dotalist,tiff_data,tiff_basename,outfolderpath,im_geotrans, im_proj):
|
||||
"""
|
||||
切分标签,输出结果与文件
|
||||
:param clusterDict:
|
||||
:param dotalist:
|
||||
:param tiff_data:
|
||||
:param tiff_name:
|
||||
:param outfolderpath:
|
||||
:return:
|
||||
"""
|
||||
for cid in clusterDict:
|
||||
sx, sy = clusterDict[cid]["p"]
|
||||
sliceData = tiff_data[sy:(sy + 1024), sx:(sx + 1024)]
|
||||
outbinname="{}_{}.bin".format(tiff_basename,str(cid).zfill(3))
|
||||
outlabelname="{}_{}.txt".format(tiff_basename,str(cid).zfill(3))
|
||||
# 获取样本列表
|
||||
outdotalist=[]
|
||||
for did in clusterDict[cid]["id"] :
|
||||
x1=dotalist[did].x1-sx
|
||||
x2=dotalist[did].x2-sx
|
||||
x3=dotalist[did].x3-sx
|
||||
x4=dotalist[did].x4-sx
|
||||
y1=dotalist[did].y1-sy
|
||||
y2=dotalist[did].y2-sy
|
||||
y3=dotalist[did].y3-sy
|
||||
y4=dotalist[did].y4-sy
|
||||
tempdota=createDota(x1,y1,x2,y2,x3,y3,x4,y4,dotalist[did].clsname,dotalist[did].difficulty)
|
||||
outdotalist.append(tempdota)
|
||||
|
||||
outlabelpath=os.path.join(outfolderpath,outlabelname)
|
||||
outbinpath=os.path.join(outfolderpath,outbinname)
|
||||
|
||||
temp_im_geotrans=[tempi for tempi in im_geotrans]
|
||||
# 处理 0,3
|
||||
temp_im_geotrans[0]=im_geotrans[0]+sx*im_geotrans[1]+im_geotrans[2]*sy # x
|
||||
temp_im_geotrans[3]=im_geotrans[3]+sx*im_geotrans[4]+im_geotrans[5]*sy # y
|
||||
write_envi(sliceData,temp_im_geotrans,im_proj,outbinpath)
|
||||
writerDotaFile(outdotalist,outlabelpath)
|
||||
|
||||
##########################################################################
|
||||
# 处理流程图
|
||||
##########################################################################
|
||||
def DataSampleSliceRasterProcess(inbinfile,labelfilepath,outfolderpath,methodstr,filterlabels):
|
||||
tiff_proj, tiff_trans, tiff_data = read_tif(inbinfile)
|
||||
tiff_inv_trans = gdal.InvGeoTransform(tiff_trans)
|
||||
dotalist=label2pixelpoints(labelfilepath,tiff_inv_trans,methodstr,filterlabels) # 获取坐标
|
||||
imgheight, imgwidth=tiff_data.shape
|
||||
clusterDict=getclusterDict(dotalist,imgheight,imgwidth)
|
||||
# drawSliceRasterPrivew(tiff_data, dotalist, clusterDict)
|
||||
ncols=int(len(clusterDict)/9+1)
|
||||
# drawSlictplot(clusterDict, dotalist, tiff_data, 9, ncols)
|
||||
tiff_name=os.path.basename(inbinfile)
|
||||
tiff_basename=os.path.splitext(tiff_name)[0]
|
||||
slictDataAndOutlabel(clusterDict, dotalist, tiff_data, tiff_basename, outfolderpath, tiff_trans, tiff_proj)
|
||||
|
||||
pass
|
||||
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inbinfile',type=str,default=r'F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.bin', help='输入tiff的bin文件')
|
||||
parser.add_argument('-l', '--labelfilepath',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\标注\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01_LC.txt", help='输入标注')
|
||||
parser.add_argument('-o', '--outfolderpath',type=str,default=r'F:\天仪SAR卫星数据集\舰船数据\切片结果', help='切片文件夹地址')
|
||||
parser.add_argument('-f', '--filterlabel',type=str,default=r'JLC;MLC', help='标签过滤')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--geolabel',
|
||||
action='store_const',
|
||||
const='geolabel',
|
||||
dest='method',
|
||||
help='标注坐标点为地理坐标'
|
||||
)
|
||||
group.add_argument(
|
||||
'--pixellabel',
|
||||
action='store_const',
|
||||
const='pixellabel',
|
||||
dest='method',
|
||||
help='标注坐标系统为输入影像的像空间坐标'
|
||||
)
|
||||
parser.set_defaults(method='geolabel')
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
inbinfile=parser.inbinfile
|
||||
labelfilepath=parser.labelfilepath
|
||||
outfolderpath=parser.outfolderpath
|
||||
methodstr= parser.method
|
||||
filterlabels=parser.filterlabel.strip().split(';')
|
||||
print('inbinfile=',inbinfile)
|
||||
print('labelfilepath=',labelfilepath)
|
||||
print('outfolderpath=',outfolderpath)
|
||||
print('methodstr=',methodstr)
|
||||
print('filterlabels=',filterlabels)
|
||||
DataSampleSliceRasterProcess(inbinfile, labelfilepath, outfolderpath,methodstr,filterlabels)
|
||||
print("样本切分完成")
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,102 @@
|
|||
|
||||
import os
|
||||
import argparse
|
||||
|
||||
import numpy as np
|
||||
|
||||
"""
|
||||
Dota数据集标注
|
||||
每条标注数据应包含:
|
||||
+前 8 个数值,表示目标的四个角点的坐标(x1, y1, x2, y2, x3, y3, x4, y4),按顺时针或逆时针顺序排列,无需进行归一化处理;
|
||||
+倒数第二列为标注的目标类别名称,如:jun_ship等;
|
||||
+最后一列为识别目标的难易程度(difficulty)
|
||||
|
||||
提供数据集标注
|
||||
|
||||
"""
|
||||
class DotaObj(object):
|
||||
def __init__(self, x1, y1, x2, y2, x3, y3, x4, y4,clsname,difficulty):
|
||||
self.x1=x1
|
||||
self.y1=y1
|
||||
self.x2=x2
|
||||
self.y2=y2
|
||||
self.x3=x3
|
||||
self.y3=y3
|
||||
self.x4=x4
|
||||
self.y4=y4
|
||||
self.clsname=clsname
|
||||
self.difficulty=difficulty
|
||||
def __str__(self):
|
||||
return "{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}".format(
|
||||
self.x1,self.y1,
|
||||
self.x2,self.y2,
|
||||
self.x3,self.y3,
|
||||
self.x4,self.y4,
|
||||
self.clsname,self.difficulty
|
||||
)
|
||||
def getCenter(self):
|
||||
CenterX=np.mean([self.x1,self.x2,self.x3,self.x4])
|
||||
CenterY=np.mean([self.y1,self.y2,self.y3,self.y4])
|
||||
return [CenterX,CenterY]
|
||||
|
||||
|
||||
def createDota(x1, y1, x2, y2, x3, y3, x4, y4,clsname,difficulty):
|
||||
return DotaObj(x1, y1, x2, y2, x3, y3, x4, y4,clsname,difficulty) # 8+2
|
||||
|
||||
|
||||
def readDotaFile(dotafilepath,filterlabels=None):
|
||||
content=None
|
||||
with open(dotafilepath,'r',encoding="utf-8") as fp:
|
||||
content=fp.read()
|
||||
contentlines=content.split("\n")
|
||||
# 逐行分解
|
||||
result=[]
|
||||
for linestr in contentlines:
|
||||
if linestr=="":
|
||||
continue
|
||||
linestr=linestr.replace("\t"," ")
|
||||
linestr=linestr.replace(" "," ")
|
||||
linemetas=linestr.split(" ")
|
||||
if(len(linemetas)>=10):
|
||||
x1=float(linemetas[0])
|
||||
y1=float(linemetas[1])
|
||||
x2=float(linemetas[2])
|
||||
y2=float(linemetas[3])
|
||||
x3=float(linemetas[4])
|
||||
y3=float(linemetas[5])
|
||||
x4=float(linemetas[6])
|
||||
y4=float(linemetas[7])
|
||||
clsname=linemetas[8]
|
||||
difficulty=linemetas[9]
|
||||
if filterlabels is None or clsname.strip() in filterlabels:
|
||||
result.append(createDota(x1, y1, x2, y2, x3, y3, x4, y4, clsname,difficulty))
|
||||
elif (len(linemetas)>=8):
|
||||
x1=float(linemetas[0])
|
||||
y1=float(linemetas[1])
|
||||
x2=float(linemetas[2])
|
||||
y2=float(linemetas[3])
|
||||
x3=float(linemetas[4])
|
||||
y3=float(linemetas[5])
|
||||
x4=float(linemetas[6])
|
||||
y4=float(linemetas[7])
|
||||
clsname="MLC"
|
||||
difficulty="0"
|
||||
if filterlabels is None or clsname.strip() in filterlabels:
|
||||
result.append(createDota(x1, y1, x2, y2, x3, y3, x4, y4, clsname,difficulty))
|
||||
else:
|
||||
print("parse result: ", linestr)
|
||||
return result
|
||||
|
||||
|
||||
def writerDotaFile(dotalist,filepath):
|
||||
with open(filepath,'a',encoding="utf-8") as fp:
|
||||
for dota in dotalist:
|
||||
if isinstance(dota,DotaObj):
|
||||
fp.write("{}\n".format(str(dota)))
|
||||
else:
|
||||
fp.write("{0} {1} {2} {3} {4} {5} {6} {7} {8} {9}\n".format(
|
||||
dota[0],dota[1],dota[2],dota[3],dota[4],dota[5],dota[6],dota[7],dota[8],dota[9]
|
||||
))
|
||||
print("write label result: ", filepath)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
# 统计结果
|
||||
import numpy as np
|
||||
import os
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
from multiprocessing import Pool
|
||||
import argparse
|
||||
import shutil
|
||||
|
||||
def find_txt_files_pathlib(directory):
|
||||
"""
|
||||
使用pathlib.Path.rglob递归查找指定目录下所有.tif和.tiff文件
|
||||
参数:
|
||||
directory (str): 要搜索的根目录路径
|
||||
返回:
|
||||
list: 包含所有找到的.tif/.tiff文件完整路径的列表
|
||||
"""
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.txt'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
def statictNumber(inlabelfilepath):
|
||||
with open(inlabelfilepath,"r",encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
lineresult=[]
|
||||
for l in lines:
|
||||
if len(l) > 10:
|
||||
lineresult.append(l)
|
||||
return len(lineresult)
|
||||
|
||||
|
||||
def FilterLabelEmptyFile(inlabelfilepath,outlabelfolder):
|
||||
labelfilepaths=find_txt_files_pathlib(inlabelfolder)
|
||||
for labelfilepath in labelfilepaths:
|
||||
rootname=Path(labelfilepath).stem
|
||||
|
||||
tiffname=os.path.splitext(labelfilepath)[0]+".tiff"
|
||||
pngname = os.path.splitext(labelfilepath)[0] + ".png"
|
||||
|
||||
labelnum=statictNumber(labelfilepath)
|
||||
if(labelnum>=1):
|
||||
outPath=os.path.join(outlabelfolder,rootname+".txt")
|
||||
outPath2 = os.path.join(outlabelfolder, rootname + ".tiff")
|
||||
outPath3 = os.path.join(outlabelfolder, rootname + ".png")
|
||||
|
||||
shutil.copy(labelfilepath,outPath)
|
||||
|
||||
# shutil.move(labelfilepath,outPath)
|
||||
# if not os.path.exists(tiffname):
|
||||
# continue
|
||||
# shutil.move(tiffname, outPath2)
|
||||
# shutil.copy(tiffname, outPath2)
|
||||
# shutil.move(pngname, outPath3)
|
||||
# shutil.copy(pngname, outPath3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--inlabelfolder',type=str,default=r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\BB-202509190345-s3-祝鑫良 part1', help='输入tiff的bin文件')
|
||||
parser.add_argument('-o', '--outlabelfolder',type=str,default=r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\删除空标注\S3', help='切片文件夹地址')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
args = getParams()
|
||||
inlabelfolder = args.inlabelfolder
|
||||
outlabelfolder = args.outlabelfolder
|
||||
print('inlabelfolder:', inlabelfolder)
|
||||
print('outcsvpath:', outlabelfolder)
|
||||
FilterLabelEmptyFile(inlabelfolder,outlabelfolder)
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
|
||||
def shp_to_geojson(shp_path, geojson_path):
|
||||
# 设置编码选项
|
||||
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
|
||||
gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
|
||||
|
||||
# 打开Shapefile
|
||||
src_ds = ogr.Open(shp_path)
|
||||
src_layer = src_ds.GetLayer(0)
|
||||
|
||||
# 创建输出GeoJSON
|
||||
driver = ogr.GetDriverByName('GeoJSON')
|
||||
if os.path.exists(geojson_path):
|
||||
driver.DeleteDataSource(geojson_path)
|
||||
dst_ds = driver.CreateDataSource(geojson_path)
|
||||
dst_layer = dst_ds.CreateLayer('output', src_layer.GetSpatialRef())
|
||||
|
||||
# 复制字段定义
|
||||
dst_layer.CreateFields(src_layer.schema)
|
||||
|
||||
# 复制要素
|
||||
for feature in src_layer:
|
||||
dst_feature = ogr.Feature(dst_layer.GetLayerDefn())
|
||||
dst_feature.SetGeometry(feature.GetGeometryRef())
|
||||
for j in range(feature.GetFieldCount()):
|
||||
dst_feature.SetField(j, feature.GetField(j))
|
||||
dst_layer.CreateFeature(dst_feature)
|
||||
|
||||
# 清理
|
||||
dst_ds = None
|
||||
src_ds = None
|
||||
print("转换完成")
|
||||
|
||||
|
||||
# 使用示例
|
||||
shp_to_geojson('input.shp', 'output.geojson')
|
||||
|
|
@ -0,0 +1,396 @@
|
|||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
sliceSize=1024
|
||||
BlockOverLayer=0.25
|
||||
|
||||
def get_filename_without_ext(path):
|
||||
base_name = os.path.basename(path)
|
||||
if '.' not in base_name or base_name.startswith('.'):
|
||||
return base_name
|
||||
return base_name.rsplit('.', 1)[0]
|
||||
|
||||
def read_tif(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans, im_data
|
||||
|
||||
def write_envi(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Byte)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def write_tiff(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Float32)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def Strech_linear(im_data):
|
||||
im_data_dB=10*np.log10(im_data)
|
||||
immask=np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data=im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
|
||||
infmask = np.isinf(im_data_dB)
|
||||
im_data[infmask] = minvalue-100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254+1
|
||||
im_data=np.clip(im_data,0,255)
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear1(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.percentile(imvail_data,1)
|
||||
maxvalue = np.percentile(imvail_data, 99)
|
||||
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
def Strech_linear2(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 2)
|
||||
maxvalue = np.percentile(imvail_data, 98)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear5(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 5)
|
||||
maxvalue = np.percentile(imvail_data, 95)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_SquareRoot(im_data):
|
||||
# 判断是否为dB
|
||||
# immask = np.isfinite(im_data)
|
||||
# imvail_data = im_data[immask]
|
||||
# minvalue = np.percentile(imvail_data,30)
|
||||
# if minvalue<0 :
|
||||
# im_data=np.power(10.0,im_data/10.0)
|
||||
|
||||
im_data=np.sqrt(im_data)
|
||||
immask = np.isfinite(im_data)
|
||||
imvail_data = im_data[immask]
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
minvalue_01Prec = np.percentile(imvail_data, 0.1) # 20250904 1%拉伸
|
||||
maxvalue_999Prec = np.percentile(imvail_data, 99.9)
|
||||
print('sqrt root min - max ', minvalue,maxvalue)
|
||||
if (maxvalue-minvalue)/(maxvalue_999Prec-minvalue_01Prec)>3: # 表示 拉伸之后,像素值绝大部分很有可能集中在 80
|
||||
minvalue=minvalue_01Prec
|
||||
maxvalue=maxvalue_999Prec
|
||||
print('sqrt root min(0.1) - max(99.9) ', minvalue, maxvalue)
|
||||
|
||||
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def DataStrech(im_data,strechmethod):
|
||||
# [,"Linear1","Linear2","Linear5","SquareRoot"]
|
||||
if strechmethod == "Linear" :
|
||||
return Strech_linear(im_data)
|
||||
elif strechmethod == "Linear1":
|
||||
return Strech_linear1(im_data)
|
||||
elif strechmethod == "Linear2":
|
||||
return Strech_linear2(im_data)
|
||||
elif strechmethod == "Linear5":
|
||||
return Strech_linear5(im_data)
|
||||
elif strechmethod == "SquareRoot":
|
||||
return Strech_SquareRoot(im_data)
|
||||
else:
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
|
||||
# 文件模式
|
||||
def stretchProcess(infilepath,outfilepath,strechmethod):
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
envifilepath=get_filename_without_ext(outfilepath)+".bin"
|
||||
envifilepath=os.path.join(os.path.dirname(outfilepath),envifilepath)
|
||||
im_data = DataStrech(im_data,strechmethod)
|
||||
im_data = im_data.astype(np.uint8)
|
||||
write_envi(im_data,im_Geotrans,im_proj,envifilepath)
|
||||
Image.fromarray(im_data).save(outfilepath,compress_level=0)
|
||||
print("图像拉伸处理结束")
|
||||
|
||||
|
||||
#切片模式
|
||||
def getSlicePoints(h):
|
||||
n = int(math.floor((h - 1024) * 1.2 / sliceSize))
|
||||
step=int(math.ceil((h-1024)/n))
|
||||
ti=list(range(0,h-1024,step))
|
||||
ti.append(h-1024)
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return ti
|
||||
|
||||
|
||||
def getsliceGeotrans(GeoTransform,Xpixel,Ypixel):
|
||||
XGeo = GeoTransform[0]+GeoTransform[1]*Xpixel+GeoTransform[2]*Ypixel
|
||||
YGeo = GeoTransform[3]+GeoTransform[4]*Xpixel+GeoTransform[5]*Ypixel
|
||||
result=[
|
||||
XGeo,GeoTransform[1],GeoTransform[2],
|
||||
YGeo,GeoTransform[4],GeoTransform[5]
|
||||
]
|
||||
return result
|
||||
|
||||
|
||||
def is_all_same(lst):
|
||||
arr = np.array(lst)
|
||||
# arr_num=arr.size
|
||||
sum_data=np.sum(arr != arr[0])
|
||||
return sum_data<400
|
||||
|
||||
def getNextSliceNumber(n,sliceSize,overlap=0.25):
|
||||
step=int(sliceSize*(1-overlap))+1
|
||||
ti = list(range(0, n, step))
|
||||
newN= n if ti[-1]+1024 < n else ti[-1]+1024
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return newN,ti
|
||||
|
||||
def sliceDataset(rootname,im_data,src_im_data, im_Geotrans, im_proj, outfolder):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
|
||||
h,w=im_data.shape
|
||||
nextH,ht=getNextSliceNumber(h,sliceSize,BlockOverLayer)
|
||||
nextW,wt=getNextSliceNumber(w,sliceSize,BlockOverLayer)
|
||||
padH=nextH-h
|
||||
padW=nextW-w
|
||||
im_data=np.pad(im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
src_im_data=np.pad(src_im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
slice_ID=0
|
||||
for hi in ht:
|
||||
for wi in wt:
|
||||
geotrans_temp=getsliceGeotrans(im_Geotrans,wi,hi)
|
||||
im_data_temp=im_data[hi:hi+1024,wi:wi+1024]
|
||||
src_im_data_temp=src_im_data[hi:hi+1024,wi:wi+1024]
|
||||
slice_ID = slice_ID + 1
|
||||
if not is_all_same(im_data_temp):
|
||||
sliceBinPath=os.path.join(binfolder, rootname+"_"+str(slice_ID).zfill(4)+".tiff")
|
||||
slicepngPath=os.path.join(pngfolder, rootname+"_"+str(slice_ID).zfill(4)+".png")
|
||||
slicesrctiffPath=os.path.join(tifffolder, rootname+"_"+str(slice_ID).zfill(4)+".tiff")
|
||||
|
||||
write_tiff(src_im_data_temp, geotrans_temp, im_proj, slicesrctiffPath)
|
||||
write_envi(im_data_temp,geotrans_temp,im_proj,sliceBinPath)
|
||||
Image.fromarray(im_data_temp).save(slicepngPath,compress_level=0)
|
||||
|
||||
print("图像切片结束")
|
||||
|
||||
|
||||
def stretchSliceProcess(infilepath, outfolder, strechmethod):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
if not os.path.exists(binfolder):
|
||||
os.makedirs(binfolder)
|
||||
if not os.path.exists(pngfolder):
|
||||
os.makedirs(pngfolder)
|
||||
if not os.path.exists(tifffolder):
|
||||
os.makedirs(tifffolder)
|
||||
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
src_im_data=im_data*1.0
|
||||
im_data = DataStrech(im_data,strechmethod) # 拉伸
|
||||
im_data = im_data.astype(np.uint8)
|
||||
rootname=Path(infilepath).stem
|
||||
allImagePath=os.path.join(outfolder, rootname+"_all.png")
|
||||
Image.fromarray(im_data).save(allImagePath,compress_level=0)
|
||||
sliceDataset(rootname,im_data, src_im_data,im_Geotrans, im_proj, outfolder)
|
||||
print("图像切片与拉伸完成")
|
||||
pass
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--infile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.tiff", help='输入shapefile文件')
|
||||
# parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.png", help='输出geojson文件')
|
||||
parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\切片结果", help='输出geojson文件')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--filemode',
|
||||
action='store_const',
|
||||
const='filemode',
|
||||
dest='mode',
|
||||
help='文件模式'
|
||||
)
|
||||
group.add_argument(
|
||||
'--slicemode',
|
||||
action='store_const',
|
||||
const='slicemode',
|
||||
dest='mode',
|
||||
help='切片模式'
|
||||
)
|
||||
parser.set_defaults(mode='slicemode')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--Linear',
|
||||
action='store_const',
|
||||
const='Linear',
|
||||
dest='method',
|
||||
help='线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear1prec',
|
||||
action='store_const',
|
||||
const='Linear1',
|
||||
dest='method',
|
||||
help='1%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear2prec',
|
||||
action='store_const',
|
||||
const='Linear2',
|
||||
dest='method',
|
||||
help='2%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear5prec',
|
||||
action='store_const',
|
||||
const='Linear5',
|
||||
dest='method',
|
||||
help='5%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--SquareRoot',
|
||||
action='store_const',
|
||||
const='SquareRoot',
|
||||
dest='method',
|
||||
help='平方根拉伸'
|
||||
)
|
||||
parser.set_defaults(method='SquareRoot')
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
intiffPath=parser.infile
|
||||
modestr=parser.mode
|
||||
methodstr = parser.method
|
||||
if modestr == "filemode":
|
||||
outbinPath = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfile=', outbinPath)
|
||||
print('method=', methodstr)
|
||||
stretchProcess(intiffPath, outbinPath, methodstr)
|
||||
elif modestr == "slicemode":
|
||||
outfolder = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfolder=', outfolder)
|
||||
print('method=', methodstr)
|
||||
stretchSliceProcess(intiffPath, outfolder, methodstr)
|
||||
pass
|
||||
else:
|
||||
print("模式错误")
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,399 @@
|
|||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
sliceSize=1024
|
||||
BlockOverLayer=0.25
|
||||
|
||||
def get_filename_without_ext(path):
|
||||
base_name = os.path.basename(path)
|
||||
if '.' not in base_name or base_name.startswith('.'):
|
||||
return base_name
|
||||
return base_name.rsplit('.', 1)[0]
|
||||
|
||||
def read_tif(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans, im_data
|
||||
|
||||
def write_envi(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Byte)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def write_tiff(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Float32)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def Strech_linear(im_data):
|
||||
im_data_dB=10*np.log10(im_data)
|
||||
immask=np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data=im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
|
||||
infmask = np.isinf(im_data_dB)
|
||||
im_data[infmask] = minvalue-100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254+1
|
||||
im_data=np.clip(im_data,0,255)
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear1(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.percentile(imvail_data,1)
|
||||
maxvalue = np.percentile(imvail_data, 99)
|
||||
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
def Strech_linear2(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 2)
|
||||
maxvalue = np.percentile(imvail_data, 98)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear5(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 5)
|
||||
maxvalue = np.percentile(imvail_data, 95)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_SquareRoot(im_data):
|
||||
# 判断是否为dB
|
||||
# immask = np.isfinite(im_data)
|
||||
# imvail_data = im_data[immask]
|
||||
# minvalue = np.percentile(imvail_data,30)
|
||||
# if minvalue<0 :
|
||||
# im_data=np.power(10.0,im_data/10.0)
|
||||
|
||||
im_data=np.sqrt(im_data)
|
||||
immask = np.isfinite(im_data)
|
||||
imvail_data = im_data[immask]
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
minvalue_01Prec = np.percentile(imvail_data, 0.1) # 20250904 1%拉伸
|
||||
maxvalue_999Prec = np.percentile(imvail_data, 99.9)
|
||||
print('sqrt root min - max ', minvalue,maxvalue)
|
||||
if (maxvalue-minvalue)/(maxvalue_999Prec-minvalue_01Prec)>3: # 表示 拉伸之后,像素值绝大部分很有可能集中在 80
|
||||
minvalue=minvalue_01Prec
|
||||
maxvalue=maxvalue_999Prec
|
||||
print('sqrt root min(0.1) - max(99.9) ', minvalue, maxvalue)
|
||||
|
||||
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def DataStrech(im_data,strechmethod):
|
||||
# [,"Linear1","Linear2","Linear5","SquareRoot"]
|
||||
if strechmethod == "Linear" :
|
||||
return Strech_linear(im_data)
|
||||
elif strechmethod == "Linear1":
|
||||
return Strech_linear1(im_data)
|
||||
elif strechmethod == "Linear2":
|
||||
return Strech_linear2(im_data)
|
||||
elif strechmethod == "Linear5":
|
||||
return Strech_linear5(im_data)
|
||||
elif strechmethod == "SquareRoot":
|
||||
return Strech_SquareRoot(im_data)
|
||||
else:
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
|
||||
# 文件模式
|
||||
def stretchProcess(infilepath,outfilepath,strechmethod):
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
envifilepath=get_filename_without_ext(outfilepath)+".bin"
|
||||
envifilepath=os.path.join(os.path.dirname(outfilepath),envifilepath)
|
||||
im_data = DataStrech(im_data,strechmethod)
|
||||
im_data = im_data.astype(np.uint8)
|
||||
write_envi(im_data,im_Geotrans,im_proj,envifilepath)
|
||||
Image.fromarray(im_data).save(outfilepath,compress_level=0)
|
||||
print("图像拉伸处理结束")
|
||||
|
||||
|
||||
#切片模式
|
||||
def getSlicePoints(h):
|
||||
n = int(math.floor((h - 1024) * 1.2 / sliceSize))
|
||||
step=int(math.ceil((h-1024)/n))
|
||||
ti=list(range(0,h-1024,step))
|
||||
ti.append(h-1024)
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return ti
|
||||
|
||||
|
||||
def getsliceGeotrans(GeoTransform,Xpixel,Ypixel):
|
||||
XGeo = GeoTransform[0]+GeoTransform[1]*Xpixel+GeoTransform[2]*Ypixel
|
||||
YGeo = GeoTransform[3]+GeoTransform[4]*Xpixel+GeoTransform[5]*Ypixel
|
||||
result=[
|
||||
XGeo,GeoTransform[1],GeoTransform[2],
|
||||
YGeo,GeoTransform[4],GeoTransform[5]
|
||||
]
|
||||
return result
|
||||
|
||||
|
||||
def is_all_same(lst):
|
||||
arr = np.array(lst)
|
||||
# arr_num=arr.size
|
||||
sum_data=np.sum(arr != arr[0])
|
||||
return sum_data<400
|
||||
|
||||
def getNextSliceNumber(n,sliceSize,overlap=0.25):
|
||||
step=int(sliceSize*(1-overlap))+1
|
||||
ti = list(range(0, n, step))
|
||||
newN= n if ti[-1]+1024 < n else ti[-1]+1024
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return newN,ti
|
||||
|
||||
def sliceDataset(rootname,im_data,src_im_data, im_Geotrans, im_proj, outfolder):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
|
||||
|
||||
h,w=im_data.shape
|
||||
nextH,ht=getNextSliceNumber(h,sliceSize,BlockOverLayer)
|
||||
nextW,wt=getNextSliceNumber(w,sliceSize,BlockOverLayer)
|
||||
padH=nextH-h
|
||||
padW=nextW-w
|
||||
im_data=np.pad(im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
src_im_data=np.pad(src_im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
slice_ID=0
|
||||
for hi in ht:
|
||||
for wi in wt:
|
||||
geotrans_temp=getsliceGeotrans(im_Geotrans,wi,hi)
|
||||
im_data_temp=im_data[hi:hi+1024,wi:wi+1024]
|
||||
src_im_data_temp=src_im_data[hi:hi+1024,wi:wi+1024]
|
||||
slice_ID = slice_ID + 1
|
||||
if not is_all_same(im_data_temp):
|
||||
sliceBinPath=os.path.join(binfolder, rootname+"_"+str(slice_ID).zfill(4)+".tiff")
|
||||
slicepngPath=os.path.join(pngfolder, rootname+"_"+str(slice_ID).zfill(4)+".png")
|
||||
slicesrctiffPath=os.path.join(tifffolder, rootname+"_"+str(slice_ID).zfill(4)+".tiff")
|
||||
|
||||
write_tiff(src_im_data_temp, geotrans_temp, im_proj, slicesrctiffPath)
|
||||
write_envi(im_data_temp,geotrans_temp,im_proj,sliceBinPath)
|
||||
Image.fromarray(im_data_temp).save(slicepngPath,compress_level=0)
|
||||
|
||||
print("图像切片结束")
|
||||
|
||||
|
||||
def stretchSliceProcess(infilepath, outfolder, strechmethod):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
allpngfolder = os.path.join(outfolder, "allpngfolder")
|
||||
if not os.path.exists(binfolder):
|
||||
os.makedirs(binfolder)
|
||||
if not os.path.exists(pngfolder):
|
||||
os.makedirs(pngfolder)
|
||||
if not os.path.exists(tifffolder):
|
||||
os.makedirs(tifffolder)
|
||||
if not os.path.exists(allpngfolder):
|
||||
os.makedirs(allpngfolder)
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
src_im_data=im_data*1.0
|
||||
im_data = DataStrech(im_data,strechmethod) # 拉伸
|
||||
im_data = im_data.astype(np.uint8)
|
||||
rootname=Path(infilepath).stem
|
||||
allImagePath=os.path.join(allpngfolder, rootname+"_all.png")
|
||||
Image.fromarray(im_data).save(allImagePath,compress_level=0)
|
||||
sliceDataset(rootname,im_data, src_im_data,im_Geotrans, im_proj, outfolder)
|
||||
print("图像切片与拉伸完成")
|
||||
pass
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--infile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.tiff", help='输入shapefile文件')
|
||||
# parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.png", help='输出geojson文件')
|
||||
parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\切片结果", help='输出geojson文件')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--filemode',
|
||||
action='store_const',
|
||||
const='filemode',
|
||||
dest='mode',
|
||||
help='文件模式'
|
||||
)
|
||||
group.add_argument(
|
||||
'--slicemode',
|
||||
action='store_const',
|
||||
const='slicemode',
|
||||
dest='mode',
|
||||
help='切片模式'
|
||||
)
|
||||
parser.set_defaults(mode='slicemode')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--Linear',
|
||||
action='store_const',
|
||||
const='Linear',
|
||||
dest='method',
|
||||
help='线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear1prec',
|
||||
action='store_const',
|
||||
const='Linear1',
|
||||
dest='method',
|
||||
help='1%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear2prec',
|
||||
action='store_const',
|
||||
const='Linear2',
|
||||
dest='method',
|
||||
help='2%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear5prec',
|
||||
action='store_const',
|
||||
const='Linear5',
|
||||
dest='method',
|
||||
help='5%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--SquareRoot',
|
||||
action='store_const',
|
||||
const='SquareRoot',
|
||||
dest='method',
|
||||
help='平方根拉伸'
|
||||
)
|
||||
parser.set_defaults(method='SquareRoot')
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
intiffPath=parser.infile
|
||||
modestr=parser.mode
|
||||
methodstr = parser.method
|
||||
if modestr == "filemode":
|
||||
outbinPath = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfile=', outbinPath)
|
||||
print('method=', methodstr)
|
||||
stretchProcess(intiffPath, outbinPath, methodstr)
|
||||
elif modestr == "slicemode":
|
||||
outfolder = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfolder=', outfolder)
|
||||
print('method=', methodstr)
|
||||
stretchSliceProcess(intiffPath, outfolder, methodstr)
|
||||
pass
|
||||
else:
|
||||
print("模式错误")
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,405 @@
|
|||
"""
|
||||
|
||||
2025.09.16 切片增加后缀 _image.png _image.tiff
|
||||
|
||||
|
||||
"""
|
||||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import math
|
||||
from pathlib import Path
|
||||
|
||||
sliceSize=1024
|
||||
BlockOverLayer=0.25
|
||||
|
||||
def get_filename_without_ext(path):
|
||||
base_name = os.path.basename(path)
|
||||
if '.' not in base_name or base_name.startswith('.'):
|
||||
return base_name
|
||||
return base_name.rsplit('.', 1)[0]
|
||||
|
||||
def read_tif(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans, im_data
|
||||
|
||||
def write_envi(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Byte)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def write_tiff(im_data, im_geotrans, im_proj, output_path):
|
||||
"""
|
||||
将数组数据写入ENVI格式文件
|
||||
:param im_data: 输入的numpy数组(2D或3D)
|
||||
:param im_geotrans: 仿射变换参数(6元组)
|
||||
:param im_proj: 投影信息(WKT字符串)
|
||||
:param output_path: 输出文件路径(无需扩展名,会自动生成.dat和.hdr)
|
||||
"""
|
||||
im_bands = 1
|
||||
im_height, im_width = im_data.shape
|
||||
# 创建ENVI格式驱动
|
||||
driver = gdal.GetDriverByName("GTiff")
|
||||
dataset = driver.Create(output_path, im_width, im_height, 1, gdal.GDT_Float32)
|
||||
|
||||
if dataset is not None:
|
||||
dataset.SetGeoTransform(im_geotrans) # 设置地理变换参数
|
||||
dataset.SetProjection(im_proj) # 设置投影
|
||||
|
||||
dataset.GetRasterBand(1).WriteArray(im_data)
|
||||
|
||||
dataset.FlushCache() # 确保数据写入磁盘
|
||||
dataset = None # 关闭文件
|
||||
|
||||
|
||||
def Strech_linear(im_data):
|
||||
im_data_dB=10*np.log10(im_data)
|
||||
immask=np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data=im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
|
||||
infmask = np.isinf(im_data_dB)
|
||||
im_data[infmask] = minvalue-100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254+1
|
||||
im_data=np.clip(im_data,0,255)
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear1(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB=0
|
||||
|
||||
minvalue=np.percentile(imvail_data,1)
|
||||
maxvalue = np.percentile(imvail_data, 99)
|
||||
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
def Strech_linear2(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 2)
|
||||
maxvalue = np.percentile(imvail_data, 98)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_linear5(im_data):
|
||||
im_data_dB = 10 * np.log10(im_data)
|
||||
immask = np.isfinite(im_data_dB)
|
||||
infmask = np.isinf(im_data_dB)
|
||||
imvail_data = im_data[immask]
|
||||
im_data_dB = 0
|
||||
|
||||
minvalue = np.percentile(imvail_data, 5)
|
||||
maxvalue = np.percentile(imvail_data, 95)
|
||||
|
||||
im_data[infmask] = minvalue - 100
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def Strech_SquareRoot(im_data):
|
||||
# 判断是否为dB
|
||||
# immask = np.isfinite(im_data)
|
||||
# imvail_data = im_data[immask]
|
||||
# minvalue = np.percentile(imvail_data,30)
|
||||
# if minvalue<0 :
|
||||
# im_data=np.power(10.0,im_data/10.0)
|
||||
|
||||
im_data=np.sqrt(im_data)
|
||||
immask = np.isfinite(im_data)
|
||||
imvail_data = im_data[immask]
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
minvalue_01Prec = np.percentile(imvail_data, 2) # 20250904 1%拉伸
|
||||
maxvalue_999Prec = np.percentile(imvail_data, 98)
|
||||
print('sqrt root min - max ', minvalue,maxvalue)
|
||||
if (maxvalue-minvalue)/(maxvalue_999Prec-minvalue_01Prec)>3: # 表示 拉伸之后,像素值绝大部分很有可能集中在 80
|
||||
minvalue=minvalue_01Prec
|
||||
maxvalue=maxvalue_999Prec
|
||||
print('sqrt root min(0.1) - max(99.9) ', minvalue, maxvalue)
|
||||
|
||||
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
def DataStrech(im_data,strechmethod):
|
||||
# [,"Linear1","Linear2","Linear5","SquareRoot"]
|
||||
if strechmethod == "Linear" :
|
||||
return Strech_linear(im_data)
|
||||
elif strechmethod == "Linear1":
|
||||
return Strech_linear1(im_data)
|
||||
elif strechmethod == "Linear2":
|
||||
return Strech_linear2(im_data)
|
||||
elif strechmethod == "Linear5":
|
||||
return Strech_linear5(im_data)
|
||||
elif strechmethod == "SquareRoot":
|
||||
return Strech_SquareRoot(im_data)
|
||||
else:
|
||||
return im_data.astype(np.uint8)
|
||||
|
||||
|
||||
|
||||
# 文件模式
|
||||
def stretchProcess(infilepath,outfilepath,strechmethod):
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
envifilepath=get_filename_without_ext(outfilepath)+".bin"
|
||||
envifilepath=os.path.join(os.path.dirname(outfilepath),envifilepath)
|
||||
im_data = DataStrech(im_data,strechmethod)
|
||||
im_data = im_data.astype(np.uint8)
|
||||
write_envi(im_data,im_Geotrans,im_proj,envifilepath)
|
||||
Image.fromarray(im_data).save(outfilepath,compress_level=0)
|
||||
print("图像拉伸处理结束")
|
||||
|
||||
|
||||
#切片模式
|
||||
def getSlicePoints(h):
|
||||
n = int(math.floor((h - 1024) * 1.2 / sliceSize))
|
||||
step=int(math.ceil((h-1024)/n))
|
||||
ti=list(range(0,h-1024,step))
|
||||
ti.append(h-1024)
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return ti
|
||||
|
||||
|
||||
def getsliceGeotrans(GeoTransform,Xpixel,Ypixel):
|
||||
XGeo = GeoTransform[0]+GeoTransform[1]*Xpixel+GeoTransform[2]*Ypixel
|
||||
YGeo = GeoTransform[3]+GeoTransform[4]*Xpixel+GeoTransform[5]*Ypixel
|
||||
result=[
|
||||
XGeo,GeoTransform[1],GeoTransform[2],
|
||||
YGeo,GeoTransform[4],GeoTransform[5]
|
||||
]
|
||||
return result
|
||||
|
||||
|
||||
def is_all_same(lst):
|
||||
arr = np.array(lst)
|
||||
# arr_num=arr.size
|
||||
sum_data=np.sum(arr != arr[0])
|
||||
return sum_data<400
|
||||
|
||||
def getNextSliceNumber(n,sliceSize,overlap=0.25):
|
||||
step=int(sliceSize*(1-overlap))+1
|
||||
ti = list(range(0, n, step))
|
||||
newN= n if ti[-1]+1024 < n else ti[-1]+1024
|
||||
# 评价重叠率
|
||||
movelayer=[]
|
||||
for i in range(len(ti)-1):
|
||||
movelayer.append((ti[i] + 1024 - ti[i + 1]) / 1024 * 100.0)
|
||||
print("重叠率:",movelayer)
|
||||
return newN,ti
|
||||
|
||||
def sliceDataset(rootname,im_data,src_im_data, im_Geotrans, im_proj, outfolder):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
|
||||
|
||||
h,w=im_data.shape
|
||||
nextH,ht=getNextSliceNumber(h,sliceSize,BlockOverLayer)
|
||||
nextW,wt=getNextSliceNumber(w,sliceSize,BlockOverLayer)
|
||||
padH=nextH-h
|
||||
padW=nextW-w
|
||||
im_data=np.pad(im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
src_im_data=np.pad(src_im_data,((0,padH),(0,padW)),mode='constant',constant_values=0)
|
||||
slice_ID=0
|
||||
for hi in ht:
|
||||
for wi in wt:
|
||||
geotrans_temp=getsliceGeotrans(im_Geotrans,wi,hi)
|
||||
im_data_temp=im_data[hi:hi+1024,wi:wi+1024]
|
||||
src_im_data_temp=src_im_data[hi:hi+1024,wi:wi+1024]
|
||||
slice_ID = slice_ID + 1
|
||||
if not is_all_same(im_data_temp):
|
||||
sliceBinPath=os.path.join(binfolder, rootname+"_"+str(slice_ID).zfill(4)+"_image.tiff")
|
||||
slicepngPath=os.path.join(pngfolder, rootname+"_"+str(slice_ID).zfill(4)+"_image.png")
|
||||
slicesrctiffPath=os.path.join(tifffolder, rootname+"_"+str(slice_ID).zfill(4)+"_image.tiff")
|
||||
|
||||
write_tiff(src_im_data_temp, geotrans_temp, im_proj, slicesrctiffPath)
|
||||
write_envi(im_data_temp,geotrans_temp,im_proj,sliceBinPath)
|
||||
Image.fromarray(im_data_temp).save(slicepngPath,compress_level=0)
|
||||
|
||||
print("图像切片结束")
|
||||
|
||||
|
||||
def stretchSliceProcess(infilepath, outfolder, strechmethod):
|
||||
binfolder=os.path.join(outfolder,"unit8binfolder")
|
||||
pngfolder=os.path.join(outfolder,"pngfolder")
|
||||
tifffolder=os.path.join(outfolder,"tifffolder")
|
||||
allpngfolder = os.path.join(outfolder, "allpngfolder")
|
||||
if not os.path.exists(binfolder):
|
||||
os.makedirs(binfolder)
|
||||
if not os.path.exists(pngfolder):
|
||||
os.makedirs(pngfolder)
|
||||
if not os.path.exists(tifffolder):
|
||||
os.makedirs(tifffolder)
|
||||
if not os.path.exists(allpngfolder):
|
||||
os.makedirs(allpngfolder)
|
||||
im_proj, im_Geotrans, im_data=read_tif(infilepath)
|
||||
src_im_data=im_data*1.0
|
||||
im_data = DataStrech(im_data,strechmethod) # 拉伸
|
||||
im_data = im_data.astype(np.uint8)
|
||||
rootname=Path(infilepath).stem
|
||||
allImagePath=os.path.join(allpngfolder, rootname+"_all.png")
|
||||
Image.fromarray(im_data).save(allImagePath,compress_level=0)
|
||||
sliceDataset(rootname,im_data, src_im_data,im_Geotrans, im_proj, outfolder)
|
||||
print("图像切片与拉伸完成")
|
||||
pass
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--infile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.tiff", help='输入shapefile文件')
|
||||
# parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\bc2-sp-org-vv-20250205t032055-021998-000036-0055ee-01.png", help='输出geojson文件')
|
||||
parser.add_argument('-o', '--outfile',type=str,default=r"F:\天仪SAR卫星数据集\舰船数据\切片结果", help='输出geojson文件')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--filemode',
|
||||
action='store_const',
|
||||
const='filemode',
|
||||
dest='mode',
|
||||
help='文件模式'
|
||||
)
|
||||
group.add_argument(
|
||||
'--slicemode',
|
||||
action='store_const',
|
||||
const='slicemode',
|
||||
dest='mode',
|
||||
help='切片模式'
|
||||
)
|
||||
parser.set_defaults(mode='slicemode')
|
||||
group = parser.add_mutually_exclusive_group()
|
||||
group.add_argument(
|
||||
'--Linear',
|
||||
action='store_const',
|
||||
const='Linear',
|
||||
dest='method',
|
||||
help='线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear1prec',
|
||||
action='store_const',
|
||||
const='Linear1',
|
||||
dest='method',
|
||||
help='1%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear2prec',
|
||||
action='store_const',
|
||||
const='Linear2',
|
||||
dest='method',
|
||||
help='2%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--Linear5prec',
|
||||
action='store_const',
|
||||
const='Linear5',
|
||||
dest='method',
|
||||
help='5%线性拉伸'
|
||||
)
|
||||
group.add_argument(
|
||||
'--SquareRoot',
|
||||
action='store_const',
|
||||
const='SquareRoot',
|
||||
dest='method',
|
||||
help='平方根拉伸'
|
||||
)
|
||||
parser.set_defaults(method='SquareRoot')
|
||||
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
intiffPath=parser.infile
|
||||
modestr=parser.mode
|
||||
methodstr = parser.method
|
||||
if modestr == "filemode":
|
||||
outbinPath = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfile=', outbinPath)
|
||||
print('method=', methodstr)
|
||||
stretchProcess(intiffPath, outbinPath, methodstr)
|
||||
elif modestr == "slicemode":
|
||||
outfolder = parser.outfile
|
||||
print('infile=', intiffPath)
|
||||
print('outfolder=', outfolder)
|
||||
print('method=', methodstr)
|
||||
stretchSliceProcess(intiffPath, outfolder, methodstr)
|
||||
pass
|
||||
else:
|
||||
print("模式错误")
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
|
@ -0,0 +1,273 @@
|
|||
from osgeo import ogr
|
||||
import os
|
||||
import argparse
|
||||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
import numpy as np
|
||||
from scipy.spatial import KDTree
|
||||
from DotaOperator import DotaObj,readDotaFile,writerDotaFile,createDota
|
||||
from glob import glob
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
|
||||
|
||||
def find_tif_files_pathlib(directory):
|
||||
path = Path(directory)
|
||||
# 使用rglob递归匹配所有.tif和.tiff文件
|
||||
tif_files = list(path.rglob('*.tiff'))
|
||||
# 将Path对象转换为字符串路径
|
||||
return [str(file) for file in tif_files]
|
||||
|
||||
|
||||
def find_srcPath(srcFolder):
|
||||
root_path = Path(srcFolder)
|
||||
target_path = [folderpath for folderpath in root_path.rglob("*") if folderpath.is_dir() and folderpath.name=="0-原图"]
|
||||
tiff_files = []
|
||||
for folderpath in target_path:
|
||||
tiff_files=tiff_files+find_tif_files_pathlib(folderpath)
|
||||
|
||||
tiff_dict={}
|
||||
for filepath in tiff_files:
|
||||
rootname=Path(filepath).stem
|
||||
tiff_dict[rootname]=filepath
|
||||
|
||||
return tiff_dict
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def read_tifInfo(path):
|
||||
dataset = gdal.Open(path) # 打开TIF文件
|
||||
if dataset is None:
|
||||
print("无法打开文件,读取文件信息")
|
||||
return None, None, None
|
||||
|
||||
cols = dataset.RasterXSize # 图像宽度
|
||||
rows = dataset.RasterYSize # 图像高度
|
||||
bands = dataset.RasterCount
|
||||
im_proj = dataset.GetProjection() # 获取投影信息
|
||||
im_Geotrans = dataset.GetGeoTransform() # 获取仿射变换信息
|
||||
# im_data = dataset.ReadAsArray(0, 0, cols, rows) # 读取栅格数据为NumPy数组
|
||||
print("行数:", rows)
|
||||
print("列数:", cols)
|
||||
print("波段:", bands)
|
||||
x1=im_Geotrans[0]+im_Geotrans[1]*0
|
||||
x2=im_Geotrans[0]+im_Geotrans[1]*cols
|
||||
|
||||
y1=im_Geotrans[3]+im_Geotrans[5]*0
|
||||
y2=im_Geotrans[3]+im_Geotrans[5]*rows
|
||||
|
||||
xmin=min(x1,x2)
|
||||
xmax=max(x1,x2)
|
||||
ymin=min(y1,y2)
|
||||
ymax=max(y1,y2)
|
||||
|
||||
geoExtend=[xmin,ymin,xmax,ymax]
|
||||
del dataset # 关闭数据集
|
||||
return im_proj, im_Geotrans,geoExtend
|
||||
|
||||
def getshapefileInfo(shp_path):
|
||||
"""
|
||||
将Shapefile转换为DOTA格式
|
||||
:param shp_path: Shapefile文件路径
|
||||
"""
|
||||
|
||||
geom_points=[]
|
||||
|
||||
print("shapefile: ",shp_path)
|
||||
|
||||
# 注册所有驱动
|
||||
ogr.RegisterAll()
|
||||
|
||||
# 打开Shapefile文件
|
||||
driver = ogr.GetDriverByName('ESRI Shapefile')
|
||||
datasource = driver.Open(shp_path, 0)
|
||||
if datasource is None:
|
||||
print("无法打开Shapefile文件")
|
||||
return
|
||||
|
||||
print("layer count: ",datasource.GetLayerCount())
|
||||
for layerid in range(datasource.GetLayerCount()):
|
||||
print("layer id: ",layerid)
|
||||
# 获取图层
|
||||
layer = datasource.GetLayer(layerid)
|
||||
layer_defn=layer.GetLayerDefn()
|
||||
field_count=layer_defn.GetFieldCount()
|
||||
|
||||
print("field_count:", field_count)
|
||||
for i in range (field_count):
|
||||
field_defn=layer_defn.GetFieldDefn(i)
|
||||
field_name=field_defn.GetName()
|
||||
field_type=field_defn.GetType()
|
||||
field_type_name=field_defn.GetFieldTypeName(field_type)
|
||||
print("field_name:", field_name, field_type_name, field_type_name)
|
||||
|
||||
for feature in layer:
|
||||
geom = feature.GetGeometryRef()
|
||||
if geom.GetGeometryName() == 'POINT':
|
||||
x=geom.GetX()
|
||||
y=geom.GetY()
|
||||
geom_points.append([x,y])
|
||||
return np.array(geom_points)
|
||||
|
||||
|
||||
def getTiffsInfo(tiffnames,folderpath):
|
||||
"""
|
||||
获取所有影像的几何信息
|
||||
Args:
|
||||
tiff_paths: tiff列表
|
||||
|
||||
Returns:
|
||||
|
||||
"""
|
||||
tiffdict={}
|
||||
for tiff_name in tiffnames:
|
||||
if tiff_name.endswith(".tiff"):
|
||||
tiff_path=os.path.join(folderpath,tiff_name)
|
||||
im_proj, im_Geotrans, geoExtend=read_tifInfo(tiff_path)
|
||||
tiffdict[tiff_name]={"geoExtend":geoExtend,"geoTrans":im_Geotrans,"imProj":im_proj}
|
||||
return tiffdict
|
||||
pass
|
||||
|
||||
|
||||
def distanceCls(tiffinfos,infolderPath,shipPortTree):
|
||||
newlabelobjsresult={}
|
||||
for tiffname in tiffinfos:
|
||||
labelname=tiffname.replace(".tiff",".txt")
|
||||
labelpath=os.path.join(infolderPath,labelname)
|
||||
im_geptrans=tiffinfos[tiffname]["geoTrans"]
|
||||
# 逐一处理
|
||||
labelobjs=readDotaFile(labelpath)
|
||||
newlabelobjs=[]
|
||||
for labelobj in labelobjs:
|
||||
try:
|
||||
labelcenterP=labelobj.getCenter()
|
||||
lon=im_geptrans[0]+im_geptrans[1]*labelcenterP[0]+im_geptrans[1]*labelcenterP[1]
|
||||
lat=im_geptrans[3]+im_geptrans[5]*labelcenterP[0]+im_geptrans[5]*labelcenterP[1]
|
||||
|
||||
# 常规
|
||||
MLC_distance,index=shipPortTree["MLC"].query([lon,lat],k=1)
|
||||
JLC_distance,index=shipPortTree["JLC"].query([lon,lat],k=1)
|
||||
# JMLC_distance,index=shipPortTree["JMLC"].query([lon,lat],k=1)
|
||||
# 处理-180
|
||||
MLC_distance_180,index_180=shipPortTree["MLC"].query([lon-360,lat],k=1)
|
||||
JLC_distance_180,index_180=shipPortTree["JLC"].query([lon-360,lat],k=1)
|
||||
# JMLC_distance_180,index_180=shipPortTree["JMLC"].query([lon-360,lat],k=1)
|
||||
# 处理180
|
||||
MLC_distance180,index180=shipPortTree["MLC"].query([lon+360,lat],k=1)
|
||||
JLC_distance180,index180=shipPortTree["JLC"].query([lon+360,lat],k=1)
|
||||
# JMLC_distance180,index180=shipPortTree["JMLC"].query([lon+360,lat],k=1)
|
||||
# 取距离最近的值
|
||||
distanceArr=[MLC_distance,JLC_distance,MLC_distance180,JLC_distance180,MLC_distance180,JLC_distance180]
|
||||
minidx=np.argmin(distanceArr)
|
||||
clsname="JLC"
|
||||
if minidx %2 ==0 :
|
||||
clsname="MLC"
|
||||
else:
|
||||
clsname="JLC"
|
||||
mindistance = distanceArr[minidx]
|
||||
if mindistance * 110000 < 500 and clsname == "JLC": # 这种在范围外认为是失效的
|
||||
clsname = "MLC"
|
||||
labelobj.clsname = clsname
|
||||
newlabelobjs.append(
|
||||
{"obj":labelobj,"distance":distanceArr[minidx]*110000,"clsname":clsname}
|
||||
)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
|
||||
# 生成新的txt
|
||||
newlabelobjsresult[tiffname]=newlabelobjs
|
||||
|
||||
return newlabelobjsresult
|
||||
|
||||
def updateLabelFile(newOutputFolder,infolderPath,updatelabels):
|
||||
|
||||
Jfolderpath=os.path.join(newOutputFolder,"J")
|
||||
Mfolderpath=os.path.join(newOutputFolder,"M")
|
||||
if not os.path.exists(Jfolderpath):
|
||||
os.makedirs(Jfolderpath)
|
||||
|
||||
if not os.path.exists(Mfolderpath):
|
||||
os.makedirs(Mfolderpath)
|
||||
|
||||
|
||||
for tiffname in updatelabels:
|
||||
newlabelobjs=updatelabels[tiffname]
|
||||
updatelabelfiles=[ obj["obj"] for obj in newlabelobjs]
|
||||
JM=set([ obj["clsname"] for obj in newlabelobjs])
|
||||
print(tiffname,"类别: ",JM)
|
||||
newlabelname=tiffname.replace(".tiff",".txt")
|
||||
targetFolderPath=Mfolderpath
|
||||
if "MLC" in JM:
|
||||
targetFolderPath=Mfolderpath
|
||||
elif "JLC" in JM:
|
||||
targetFolderPath=Jfolderpath
|
||||
|
||||
newlabelpath=os.path.join(targetFolderPath,newlabelname)
|
||||
newtiffpath=os.path.join(targetFolderPath,tiffname)
|
||||
|
||||
writerDotaFile(updatelabelfiles,newlabelpath)
|
||||
shutil.copyfile(os.path.join(infolderPath,tiffname),newtiffpath)
|
||||
print("copy : ", tiffname)
|
||||
|
||||
pass
|
||||
|
||||
def SpliteProcess(srcfolderpath,infolderpath,outfolderpath,MLCPath,JLCPath,JMLCPath):
|
||||
shipPort={
|
||||
"MLC":getshapefileInfo(MLCPath),
|
||||
"JLC":getshapefileInfo(JLCPath),
|
||||
# "JMLC":getshapefileInfo(JMLCPath), # 舰船不区分 居民一体
|
||||
}
|
||||
|
||||
shipPortTree={
|
||||
"MLC":KDTree(shipPort["MLC"]),
|
||||
"JLC":KDTree(shipPort["JLC"]),
|
||||
# "JMLC":KDTree(shipPort["JMLC"]),
|
||||
}
|
||||
|
||||
# tiffds=find_srcPath(srcfolderpath)
|
||||
|
||||
tifflist=os.listdir(infolderpath)
|
||||
tiffinfos=getTiffsInfo(tifflist,infolderpath)
|
||||
updatelabels=distanceCls(tiffinfos,infolderpath,shipPortTree)
|
||||
|
||||
# 更新日志
|
||||
updateLabelFile(outfolderpath, infolderpath, updatelabels)
|
||||
|
||||
return True
|
||||
pass
|
||||
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-s','--srcfolder',type=str,default=r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口', help='输入shapefile文件')
|
||||
parser.add_argument('-i','--intiffolder',type=str,default=r'D:\TYSAR-德清院\切片结果整理', help='输入shapefile文件')
|
||||
parser.add_argument('-o', '--outfolder',type=str,default=r'D:\TYSAR-德清院\军民区分结果', help='输出geojson文件')
|
||||
parser.add_argument('-m', '--mLC',type=str,help=r'MLC', default=r'D:\TYSAR-德清院\目标点位信息更新\0828目标点位\港口(民船).shp')
|
||||
parser.add_argument('-j', '--jLC',type=str,help=r'JLC' ,default=r'D:\TYSAR-德清院\目标点位信息更新\0828目标点位\军港.shp')
|
||||
parser.add_argument('-jm', '--jmLC',type=str,help=r'MJLC', default=r'D:\TYSAR-德清院\目标点位信息更新\0828目标点位\军民一体港口.shp')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
srcfolder=parser.srcfolder
|
||||
infolder=parser.intiffolder
|
||||
outfolder=parser.outfolder
|
||||
mLCPath=parser.mLC
|
||||
jLCPath=parser.jLC
|
||||
jmLCPath=parser.jmLC
|
||||
print('srcfolder=',srcfolder)
|
||||
print('infolder=',infolder)
|
||||
print('outfolder=',outfolder)
|
||||
print('mLCPath=',mLCPath)
|
||||
print('jLCPath=',jLCPath)
|
||||
print('jmLCPath=',jmLCPath)
|
||||
SpliteProcess(srcfolder,infolder,outfolder,mLCPath,jLCPath,jmLCPath)
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
import os
|
||||
import csv
|
||||
from collections import Counter
|
||||
|
||||
# 获取当前目录下的所有txt文件
|
||||
folder_path = r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\删除空标注' # 当前文件夹
|
||||
txt_files = [f for f in os.listdir(folder_path) if f.endswith('.txt')]
|
||||
|
||||
print(f"找到 {len(txt_files)} 个txt文件:")
|
||||
for file in txt_files:
|
||||
print(f" {file}")
|
||||
|
||||
# 提取每个文件名的前50个字符
|
||||
prefixes = [filename[:50] for filename in txt_files]
|
||||
|
||||
# 统计每个前缀出现的次数
|
||||
prefix_counts = Counter(prefixes)
|
||||
|
||||
# 准备要写入CSV的数据
|
||||
csv_data = [(prefix, count) for prefix, count in prefix_counts.items()]
|
||||
|
||||
# 将结果写入CSV文件
|
||||
csv_filename = r'D:\TYSAR-德清院\unique_file_0919.csv'
|
||||
with open(csv_filename, 'w', newline='', encoding='utf-8') as csvfile:
|
||||
writer = csv.writer(csvfile)
|
||||
writer.writerow(['文件名前50个字符', '重复次数']) # 写入表头
|
||||
writer.writerows(csv_data)
|
||||
|
||||
print(f"\n已将结果保存到 {csv_filename}")
|
||||
print("\n重复统计详情:")
|
||||
for prefix, count in csv_data:
|
||||
print(f" '{prefix}': {count} 次")
|
||||
|
||||
# 显示重复的文件
|
||||
duplicates = [item for item in csv_data if item[1] > 1]
|
||||
if duplicates:
|
||||
print("\n发现的重复文件:")
|
||||
for prefix, count in duplicates:
|
||||
print(f" 前缀 '{prefix}' 出现了 {count} 次")
|
||||
else:
|
||||
print("\n未发现重复文件")
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
import os
|
||||
|
||||
|
||||
def replace_ship_in_txt_files(directory):
|
||||
"""
|
||||
遍历指定目录下的所有txt文件,将其中的'ship'替换为'civil_ship'
|
||||
|
||||
Args:
|
||||
directory (str): 要处理的目录路径
|
||||
"""
|
||||
# 获取目录下所有文件
|
||||
all_files = os.listdir(directory)
|
||||
|
||||
# 筛选出txt文件
|
||||
txt_files = [f for f in all_files if f.endswith('.txt')]
|
||||
|
||||
for filename in txt_files:
|
||||
filepath = os.path.join(directory, filename)
|
||||
|
||||
# 读取文件内容
|
||||
with open(filepath, 'r', encoding='utf-8') as file:
|
||||
content = file.read()
|
||||
|
||||
# 替换字符串
|
||||
modified_content = content.replace('civil_ship', 'civil_ship 1')
|
||||
|
||||
# 写回文件
|
||||
with open(filepath, 'w', encoding='utf-8') as file:
|
||||
file.write(modified_content)
|
||||
|
||||
print(f"已处理文件: {filename}")
|
||||
|
||||
|
||||
# 使用示例
|
||||
replace_ship_in_txt_files(r'R:\TYSAR-德清院\TYSAR-条带模式(SM)\港口\20250910-不分类\C-人工检查\删除空标注') # 请替换为你的目录路径
|
||||
|
|
@ -0,0 +1,57 @@
|
|||
import os
|
||||
import shutil
|
||||
|
||||
|
||||
def copy_matching_files(folder_A, folder_B, folder_C):
|
||||
"""
|
||||
将文件夹A和文件夹B中同名的文件复制到文件夹C
|
||||
|
||||
参数:
|
||||
folder_A: 第一个文件夹路径
|
||||
folder_B: 第二个文件夹路径
|
||||
folder_C: 目标文件夹路径
|
||||
"""
|
||||
# 确保目标文件夹存在
|
||||
if not os.path.exists(folder_C):
|
||||
os.makedirs(folder_C)
|
||||
print(f"创建目标文件夹: {folder_C}")
|
||||
|
||||
try:
|
||||
# 获取两个文件夹中的文件列表(不包含目录)
|
||||
print("A")
|
||||
files_A = [f for f in os.listdir(folder_A) if os.path.isfile(os.path.join(folder_A, f))]
|
||||
print("A")
|
||||
files_B = [f for f in os.listdir(folder_B) if os.path.isfile(os.path.join(folder_B, f))]
|
||||
print(files_B)
|
||||
# 找出两个文件夹中同名的文件
|
||||
common_files = set(files_A) & set(files_B)
|
||||
# common_files = set(files_A) - set(files_B)
|
||||
if not common_files:
|
||||
print("未找到同名文件。")
|
||||
return
|
||||
|
||||
# 复制同名文件到文件夹C
|
||||
copied_count = 0
|
||||
for file_name in common_files:
|
||||
# 这里选择从folder_A复制,你也可以改为从folder_B复制或同时复制两个版本
|
||||
source_path = os.path.join(folder_A, file_name)
|
||||
dest_path = os.path.join(folder_C, file_name)
|
||||
|
||||
shutil.copy2(source_path, dest_path)
|
||||
print(f"已复制: {file_name}")
|
||||
copied_count += 1
|
||||
|
||||
print(f"\n复制完成!共复制 {copied_count} 个文件。")
|
||||
|
||||
except Exception as e:
|
||||
print(f"操作出错: {e}")
|
||||
|
||||
|
||||
# 使用示例
|
||||
if __name__ == "__main__":
|
||||
# 请修改为你的实际路径
|
||||
folder_A = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\Group_6\png_txt" # 替换为第一个文件夹路径
|
||||
folder_B = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\剔除空标注\G6" # 替换为第二个文件夹路径
|
||||
folder_C = r"R:\TYSAR-德清院\B-模型处理-预标注\20250818-不分类-处理20250906\人工检查\Group_6\d" # 替换为目标文件夹路径
|
||||
|
||||
copy_matching_files(folder_A, folder_B, folder_C)
|
||||
|
|
@ -0,0 +1,68 @@
|
|||
import os
|
||||
import time # 如需使用时间戳可引入
|
||||
|
||||
|
||||
def add_suffix_to_files(directory, suffix="_image"):
|
||||
"""
|
||||
遍历指定目录下的所有文件,如果文件名中不包含指定后缀字符,则在文件名末尾添加该后缀。
|
||||
如果新文件名已存在,会自动在文件名中插入序号以避免冲突。
|
||||
|
||||
:param directory: 要处理的文件夹路径
|
||||
:param suffix: 要添加的后缀,默认为"_image"
|
||||
"""
|
||||
# 检查目录是否存在
|
||||
if not os.path.isdir(directory):
|
||||
print(f"错误:目录 '{directory}' 不存在。")
|
||||
return
|
||||
|
||||
# 获取目录中的所有文件(不包含子目录)
|
||||
all_files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
|
||||
|
||||
# 首先,找出所有已经包含后缀的文件,避免重复处理
|
||||
files_to_rename = []
|
||||
for filename in all_files:
|
||||
name_part, ext_part = os.path.splitext(filename)
|
||||
# 检查文件名主干中是否不包含后缀(不区分大小写)
|
||||
if suffix.lower() not in name_part.lower():
|
||||
files_to_rename.append(filename)
|
||||
else:
|
||||
print(f"⏭️ 跳过: {filename} (已包含后缀)")
|
||||
|
||||
# 遍历需要重命名的文件
|
||||
for filename in files_to_rename:
|
||||
file_path = os.path.join(directory, filename)
|
||||
name_part, ext_part = os.path.splitext(filename)
|
||||
|
||||
# 构建基础新文件名
|
||||
base_new_filename = f"{name_part}{suffix}{ext_part}"
|
||||
base_new_filepath = os.path.join(directory, base_new_filename)
|
||||
|
||||
new_filename = base_new_filename
|
||||
new_filepath = base_new_filepath
|
||||
|
||||
# 检查基础新文件名是否存在,如果存在则添加序号
|
||||
counter = 1
|
||||
while os.path.exists(new_filepath):
|
||||
# 在主干和后缀之间插入序号,例如 "file_image_1.txt"
|
||||
new_filename = f"{name_part}{suffix}_{counter}{ext_part}"
|
||||
new_filepath = os.path.join(directory, new_filename)
|
||||
counter += 1
|
||||
|
||||
# 执行重命名操作
|
||||
try:
|
||||
os.rename(file_path, new_filepath)
|
||||
# 如果最终使用的文件名与基础新文件名不同,说明添加了序号
|
||||
if new_filename != base_new_filename:
|
||||
print(f"⚠️ 重命名 (冲突解决): {filename} -> {new_filename} (原名称 {base_new_filename} 已存在)")
|
||||
else:
|
||||
print(f"✅ 已重命名: {filename} -> {new_filename}")
|
||||
except OSError as e:
|
||||
print(f"❌ 重命名 {filename} 时出错: {e}")
|
||||
|
||||
print("--- 所有文件处理完成 ---")
|
||||
|
||||
|
||||
# 使用示例
|
||||
if __name__ == "__main__":
|
||||
folder_path = r'R:\TYSAR-德清院\D-切片成果\TYSAR-条带模式(SM)\港口\切片结果整理'
|
||||
add_suffix_to_files(folder_path)
|
||||
|
|
@ -0,0 +1,98 @@
|
|||
from osgeo import ogr
|
||||
import os
|
||||
import argparse
|
||||
|
||||
def shapefile_to_dota(shp_path, output_path, class_field='class', difficulty_value=1):
|
||||
"""
|
||||
将Shapefile转换为DOTA格式
|
||||
:param shp_path: Shapefile文件路径
|
||||
:param output_path: 输出目录
|
||||
:param class_field: 类别字段名
|
||||
:param difficulty_value: 难度默认字段
|
||||
"""
|
||||
|
||||
# 注册所有驱动
|
||||
ogr.RegisterAll()
|
||||
|
||||
# 打开Shapefile文件
|
||||
driver = ogr.GetDriverByName('ESRI Shapefile')
|
||||
datasource = driver.Open(shp_path, 0)
|
||||
if datasource is None:
|
||||
print("无法打开Shapefile文件")
|
||||
return
|
||||
|
||||
# 获取图层
|
||||
layer = datasource.GetLayer()
|
||||
|
||||
output_file = output_path
|
||||
|
||||
with open(output_file, 'w',encoding="utf-8") as f:
|
||||
# 写入DOTA格式头信息(可选)
|
||||
# f.write('imagesource:unknown\n')
|
||||
# f.write('gsd:1.0\n')
|
||||
|
||||
# 遍历所有要素
|
||||
for feature in layer:
|
||||
# 获取几何对象
|
||||
geom = feature.GetGeometryRef()
|
||||
if geom is None:
|
||||
continue
|
||||
# 获取类别和难度
|
||||
try:
|
||||
class_name = feature.GetField(class_field) if feature.GetField(class_field) else 'unknown'
|
||||
except Exception as e:
|
||||
class_name="MLC"
|
||||
print(e)
|
||||
difficulty = difficulty_value
|
||||
|
||||
# 处理不同类型的几何图形
|
||||
if geom.GetGeometryName() == 'POLYGON':
|
||||
# 获取多边形外环
|
||||
ring = geom.GetGeometryRef(0)
|
||||
# 获取所有点
|
||||
points = []
|
||||
for i in range(ring.GetPointCount()):
|
||||
points.append(ring.GetPoint(i))
|
||||
|
||||
# 确保有足够的点(至少4个)
|
||||
if len(points) >= 4:
|
||||
# 取前4个点作为DOTA格式的四个角点
|
||||
# 注意: DOTA要求按顺序排列(顺时针或逆时针)
|
||||
x1, y1 = points[0][0], points[0][1]
|
||||
x2, y2 = points[1][0], points[1][1]
|
||||
x3, y3 = points[2][0], points[2][1]
|
||||
x4, y4 = points[3][0], points[3][1]
|
||||
|
||||
# 写入DOTA格式行
|
||||
line = f"{x1} {y1} {x2} {y2} {x3} {y3} {x4} {y4} {class_name} {difficulty}\n"
|
||||
f.write(line)
|
||||
|
||||
# 释放资源
|
||||
datasource.Destroy()
|
||||
print("转换完毕")
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--infile',type=str,default=r'D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01_LC.shp', help='输入shapefile文件')
|
||||
parser.add_argument('-o', '--outfile',type=str,default=r'D:\Annotation_Y\港口\聚束模式\20250505_sp\bc3-sp-org-vv-20250410t053930-020615-000034-005087-01_LC.txt', help='输出geojson文件')
|
||||
parser.add_argument('-c', '--clsname',type=str,default=r'Label', help='输出geojson文件')
|
||||
parser.add_argument('-d', '--difficulty',type=int,default=1, help='输出geojson文件')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
parser = getParams()
|
||||
inFilePath=parser.infile
|
||||
outpath=parser.outfile
|
||||
clsname=parser.clsname
|
||||
difficulty=parser.difficulty
|
||||
print('infile=',inFilePath)
|
||||
print('outfile=',outpath)
|
||||
print('clsname=',clsname)
|
||||
print('difficulty=',difficulty)
|
||||
shapefile_to_dota(inFilePath, outpath, clsname, difficulty)
|
||||
exit(2)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
exit(3)
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
from osgeo import ogr, gdal
|
||||
import os
|
||||
import argparse
|
||||
|
||||
def shp_to_geojson(shp_path, geojson_path):
|
||||
# 设置编码选项
|
||||
gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES")
|
||||
gdal.SetConfigOption("SHAPE_ENCODING", "GBK")
|
||||
|
||||
# 打开Shapefile
|
||||
src_ds = ogr.Open(shp_path)
|
||||
src_layer = src_ds.GetLayer(0)
|
||||
|
||||
# 创建输出GeoJSON
|
||||
driver = ogr.GetDriverByName('GeoJSON')
|
||||
if os.path.exists(geojson_path):
|
||||
driver.DeleteDataSource(geojson_path)
|
||||
dst_ds = driver.CreateDataSource(geojson_path)
|
||||
dst_layer = dst_ds.CreateLayer('output', src_layer.GetSpatialRef())
|
||||
|
||||
# 复制字段定义
|
||||
dst_layer.CreateFields(src_layer.schema)
|
||||
|
||||
# 复制要素
|
||||
for feature in src_layer:
|
||||
dst_feature = ogr.Feature(dst_layer.GetLayerDefn())
|
||||
dst_feature.SetGeometry(feature.GetGeometryRef())
|
||||
for j in range(feature.GetFieldCount()):
|
||||
dst_feature.SetField(j, feature.GetField(j))
|
||||
dst_layer.CreateFeature(dst_feature)
|
||||
|
||||
# 清理
|
||||
dst_ds = None
|
||||
src_ds = None
|
||||
print("转换完成")
|
||||
|
||||
def getParams():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('-i','--infile',default=r'F:\天仪SAR卫星数据集\德清院-测试-天仪提供数据\bc2-sp-org-vv-20250210t160723-022200-000120-0056b8-01_石佳宁.shp', help='输入shapefile文件')
|
||||
parser.add_argument('-o', '--outfile',default=r'F:\天仪SAR卫星数据集\德清院-测试-天仪提供数据\bc2-sp-org-vv-20250210t160723-022200-000120-0056b8-01_石佳宁.json', help='输出geojson文件')
|
||||
args = parser.parse_args()
|
||||
return args
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = getParams()
|
||||
inFilePath=parser.infile
|
||||
outpath=parser.outfile
|
||||
print('infile=',inFilePath)
|
||||
print('outfile=',outpath)
|
||||
shp_to_geojson(inFilePath, outpath)
|
||||
|
|
@ -0,0 +1,97 @@
|
|||
import rasterio
|
||||
from rasterio.windows import Window
|
||||
import geopandas as gpd
|
||||
from shapely.geometry import box
|
||||
import numpy as np
|
||||
import os
|
||||
|
||||
# 参数设置
|
||||
image_path = 'path/to/your/image.tif' # 替换为您的影像路径(20000x20000)
|
||||
shapefile_path = 'path/to/your/shapefile.shp' # 替换为您的图斑Shapefile路径
|
||||
output_dir = 'path/to/output/tiles' # 输出切片目录
|
||||
tile_size = 1024 # 固定切片大小
|
||||
max_overlap_ratio = 0.2 # 重叠小于20%
|
||||
min_step = int(tile_size * (1 - max_overlap_ratio)) # 最小步长 ≈820
|
||||
|
||||
# 创建输出目录
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
|
||||
# 读取影像
|
||||
with rasterio.open(image_path) as src:
|
||||
image_width, image_height = src.width, src.height
|
||||
assert image_width == 20000 and image_height == 20000, "影像大小不匹配"
|
||||
transform = src.transform # 地理变换矩阵
|
||||
|
||||
# 读取图斑数据(假设CRS一致)
|
||||
gdf = gpd.read_file(shapefile_path)
|
||||
# 确保图斑CRS与影像一致,如果不一致需转换:gdf = gdf.to_crs(src.crs)
|
||||
|
||||
# 初始化切片列表,避免重叠过多
|
||||
generated_windows = []
|
||||
|
||||
for idx, row in gdf.iterrows():
|
||||
geom = row.geometry # 获取单个图斑多边形
|
||||
|
||||
# 计算图斑的边界框 (minx, miny, maxx, maxy) - 像素坐标
|
||||
minx, miny, maxx, maxy = geom.bounds
|
||||
bbox_width = maxx - minx
|
||||
bbox_height = maxy - miny
|
||||
|
||||
# 如果图斑太大,无法放入单个1024x1024切片,需处理(这里简单跳过,您可修改)
|
||||
if bbox_width > tile_size or bbox_height > tile_size:
|
||||
print(f"图斑 {idx} 太大 ({bbox_width}x{bbox_height}),跳过或需多切片处理")
|
||||
continue
|
||||
|
||||
# 计算覆盖完整图斑的最小窗口:居中扩展到1024x1024
|
||||
center_x = (minx + maxx) / 2
|
||||
center_y = (miny + maxy) / 2
|
||||
half_tile = tile_size / 2
|
||||
win_minx = max(0, center_x - half_tile)
|
||||
win_miny = max(0, center_y - half_tile)
|
||||
win_maxx = min(image_width, center_x + half_tile)
|
||||
win_maxy = min(image_height, center_y + half_tile)
|
||||
|
||||
# 调整以确保正好1024x1024(如果边界不足,padding或调整)
|
||||
if win_maxx - win_minx < tile_size:
|
||||
win_minx = max(0, win_maxx - tile_size)
|
||||
if win_maxy - win_miny < tile_size:
|
||||
win_miny = max(0, win_maxy - tile_size)
|
||||
|
||||
proposed_window = Window(win_minx, win_miny, tile_size, tile_size)
|
||||
|
||||
# 检查与现有窗口的重叠,确保<20%
|
||||
too_much_overlap = False
|
||||
for existing_win in generated_windows:
|
||||
# 计算重叠区域
|
||||
overlap_x = max(0, min(win_minx + tile_size, existing_win.col_off + tile_size) - max(win_minx, existing_win.col_off))
|
||||
overlap_y = max(0, min(win_miny + tile_size, existing_win.row_off + tile_size) - max(win_miny, existing_win.row_off))
|
||||
overlap_area = overlap_x * overlap_y
|
||||
if overlap_area > (tile_size * tile_size * max_overlap_ratio):
|
||||
too_much_overlap = True
|
||||
break
|
||||
|
||||
if too_much_overlap:
|
||||
# 如果重叠太大,调整位置(这里简单跳过,您可实现更复杂的调整,如偏移步长)
|
||||
print(f"图斑 {idx} 的窗口重叠过多,跳过或调整")
|
||||
continue
|
||||
|
||||
# 添加到列表
|
||||
generated_windows.append(proposed_window)
|
||||
|
||||
# 裁剪并保存切片
|
||||
tile_data = src.read(window=proposed_window)
|
||||
tile_meta = src.meta.copy()
|
||||
tile_meta.update({
|
||||
'width': proposed_window.width,
|
||||
'height': proposed_window.height,
|
||||
'transform': rasterio.windows.transform(proposed_window, src.transform)
|
||||
})
|
||||
output_path = os.path.join(output_dir, f'tile_{idx}.tif')
|
||||
with rasterio.open(output_path, 'w', **tile_meta) as dst:
|
||||
dst.write(tile_data)
|
||||
|
||||
print(f"生成切片 {output_path},覆盖图斑 {idx}")
|
||||
|
||||
print(f"总共生成 {len(generated_windows)} 个切片")
|
||||
|
||||
# 注意:这个代码确保每个切片包含至少一个完整图斑,但可能有图斑被多个切片覆盖(如果重叠允许)。如果需要覆盖所有图斑的最优 tiling,请提供更多细节。
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
AB版本拉伸策略:
|
||||
# 判断是否为dB
|
||||
# immask = np.isfinite(im_data)
|
||||
# imvail_data = im_data[immask]
|
||||
# minvalue = np.percentile(imvail_data,30)
|
||||
# if minvalue<0 :
|
||||
# im_data=np.power(10.0,im_data/10.0)
|
||||
|
||||
im_data=np.sqrt(im_data)
|
||||
immask = np.isfinite(im_data)
|
||||
imvail_data = im_data[immask]
|
||||
|
||||
minvalue=np.nanmin(imvail_data)
|
||||
maxvalue=np.nanmax(imvail_data)
|
||||
minvalue_01Prec = np.percentile(imvail_data, 2) # 20250904 1%拉伸
|
||||
maxvalue_999Prec = np.percentile(imvail_data, 98)
|
||||
print('sqrt root min - max ', minvalue,maxvalue)
|
||||
if (maxvalue-minvalue)/(maxvalue_999Prec-minvalue_01Prec)>3: # 表示 拉伸之后,像素值绝大部分很有可能集中在 80
|
||||
minvalue=minvalue_01Prec
|
||||
maxvalue=maxvalue_999Prec
|
||||
print('sqrt root min(0.1) - max(99.9) ', minvalue, maxvalue)
|
||||
|
||||
|
||||
im_data = (im_data - minvalue) / (maxvalue - minvalue) * 254 + 1
|
||||
im_data = np.clip(im_data, 0, 255)
|
||||
|
||||
return im_data.astype(np.uint8)
|
||||
Loading…
Reference in New Issue