def generate_xml_from_all_seq(self): clear_scene_file_startswith(self.seq_name) SceneGenerate.write_range_num_for_RT(self._cfgFile) self.readParameterFileList() for filename in self.parameter_file_list: tcfgfile = os.path.join(session.get_input_dir(), filename) prifix = os.path.splitext(filename)[0] + "_" SceneGenerate.terr_generate(tcfgfile, prifix) SceneGenerate.generate_objects_file(tcfgfile, prifix) SceneGenerate.forest_generate(tcfgfile, prifix) # if len(self.parameter_file_list) > 0: # SceneGenerate.generate_objects_file(self._cfgFile, self.seq_name + "_") # SceneGenerate.forest_generate(self._cfgFile, self.seq_name + "_") # log("INFO: Generating view and illuminations.") # 输出irridiance fi = open( os.path.join(session.get_output_dir(), self.seq_name + "_" + irradiance_file), 'w') sp = SceneParser() for filename in self.parameter_file_list: tcfgfile = os.path.join(session.get_input_dir(), filename) prifix = os.path.splitext(filename)[0] + "_" irrstr = sp.parse(tcfgfile, prifix, prifix) fi.write(os.path.splitext(filename)[0] + "\n" + irrstr + "\n") log("INFO: view and illuminations generated.") fi.close()
def new_proj_indicator(): curr_dir = os.getcwd() check_file = curr_dir + os.sep + less_identifier if os.path.exists(check_file): log("This directory is already a less simulation") sys.exit(0) else: os.mkdir(check_file)
def run_seq(self): currdir = os.path.split(os.path.realpath(__file__))[0] os.environ[ 'PATH'] = currdir + '/bin/rt/' + current_rt_program + os.pathsep + os.environ[ 'PATH'] self.readParameterFileList() for filename in self.parameter_file_list: log("INFO: " + filename) tcfgfile = os.path.join(session.get_input_dir(), filename) prifix = os.path.splitext(filename)[0] f = open(tcfgfile, 'r') cfg = json.load(f) excuable = "lessrt" scene_path = session.get_scenefile_path() distFile = os.path.join(session.get_output_dir(), prifix) # parameter = " -o " + distFile scene_file_path = os.path.join(scene_path, prifix + "_" + main_scene_xml_file) # cmd = excuable + " " + os.path.join(scene_path, prifix+"_"+main_scene_xml_file) + parameter # os.system(cmd) cores = cfg["Advanced"]["number_of_cores"] if cfg["Advanced"]["network_sim"]: subprocess.call([ excuable, scene_file_path, "-o", distFile, "-p", str(cores), "-s", os.path.join(session.get_input_dir(), "server.txt") ]) else: subprocess.call([ excuable, scene_file_path, "-o", distFile, "-p", str(cores) ]) # os.system(excuable + " " + scene_file_path + " " + "-o " + distFile + " -p " + str(cores)) time.sleep(0.5) if output_format not in ("npy", "NPY"): if os.path.exists(distFile + ".npy"): self.convert_npy_to_envi(cfg, distFile, output_format) if os.path.exists(distFile + "_downwelling.npy"): self.convert_npy_to_envi(cfg, distFile + "_downwelling", output_format) if os.path.exists(distFile + "_upwelling.npy"): self.convert_npy_to_envi(cfg, distFile + "_upwelling", output_format) if os.path.exists(distFile + "_4Components.npy"): data = np.load(distFile + "_4Components.npy") dshape = data.shape if len(dshape) == 3: if dshape[2] <= 4: data = data[:, :, 0] else: data = data[:, :, 0:5] bandlist = [] RasterHelper.saveToHdr_no_transform( data, distFile + "_4Components", bandlist, output_format) os.remove(distFile + "_4Components.npy")
def new_sequencer(seq_name): seq_file = combine_file_path(os.getcwd(), seq_name + ".conf") f = open(seq_file, 'w') f.write( "{\n \"seq1\" : {\n \"obs_azimuth\" :\"LIST:0,30,60,90,120,150,180,210,240,270,300,330\"\n },\n" " \"seq2\" : {\n \"obs_zenith\" :\"LIST:0,5,15,20,25,30,35,40,45,50,55,60,65,70\"\n }\n}" ) f.close() log("Succeed.")
def __init__(self): currdir = os.path.split(os.path.realpath(__file__))[0] const_file = currdir + os.sep + "const.conf" if not os.path.exists(const_file): log("const config file does not exist.") sys.exitfunc() else: f = open(const_file, "r") self.const = json.load(f) f.close()
def newproj(): # create a indicator session.new_proj_indicator() if not os.path.exists(input_dir): os.mkdir(input_dir) # input os.mkdir(combine_file_path(input_dir, tmp_scene_file_dir)) # input/_scenefile # currdir = os.path.split(os.path.realpath(__file__))[0] # shutil.copy(combine_file_path(currdir,template_input), input_dir) os.mkdir(output_dir) log("Succeed: ", os.path.realpath(os.path.curdir))
def run_waveform(): currdir = os.path.split(os.path.realpath(__file__))[0] rt_dir = os.path.join(currdir + '/bin/rt/' + current_rt_program) os.environ['PATH'] = rt_dir + os.pathsep + os.environ['PATH'] excuable = 'lessrt' xml_filename = 'lidar_main.xml' scene_file_path = os.path.join(session.get_scenefile_path(), xml_filename) distFile = os.path.join(session.get_output_dir(), "waveform") command = [excuable, scene_file_path, '-o', distFile] log('INFO: ', command) subprocess.call(command)
def Raster2Ojb(rasterfile, dist_obj_file, offset_to_lowerest_pos=True): if os.path.exists(dist_obj_file): return dataset = gdal.Open(rasterfile) band = dataset.GetRasterBand(1) transform = dataset.GetGeoTransform() if not transform is None: pixel_x = abs(transform[1]) pixel_y = abs(transform[5]) else: log("no geo transform.") XSize = band.XSize YSize = band.YSize xExtend = XSize*pixel_x yExtend = YSize*pixel_y # save to openexr file dataarr = band.ReadAsArray(0, 0, band.XSize, band.YSize) if offset_to_lowerest_pos: dataarr = dataarr - dataarr.min() f = open(dist_obj_file,'w') for i in range(0, YSize+1): for j in range(0, XSize+1): x = " %.4f " % (0.5 * xExtend - j * pixel_x) z = " %.4f " % (0.5 * yExtend - i * pixel_y) if i < YSize and j < XSize: datavalue = " %.4f"% (dataarr[i][j]) else: datavalue = " %.4f"% (dataarr[i-1][j-1]) fstr = "v " + x + datavalue + z + "\n" f.write(fstr) for i in range(0, YSize): for j in range(0, XSize): p1 = i*(XSize+1) + j+1 p2 = (i+1)*(XSize+1) + j+1 p3 = (i+1)*(XSize+1) +j+1+1 p4 = i*(XSize+1) + j+ 1+1 fstr = "f " + str(p1) + " " + str(p2) + " " + str(p3) + " " + str(p4)+"\n" f.write(fstr) f.close()
def saveToHdr(npArray, hdrHeaderPath, dstFilePath, width, height, spatialResolution): # 从hdrHeaderPath中提取投影信息 dataset = gdal.Open(hdrHeaderPath) geotransform = dataset.GetGeoTransform() projection = dataset.GetProjection() geoTrans = [geotransform[0], spatialResolution, geotransform[2], geotransform[3], geotransform[4], -spatialResolution] if dataset is None: log("Header File not found!") return format = "ENVI" driver = gdal.GetDriverByName(format) dst_ds = driver.Create(dstFilePath, width, height, 65, gdal.GDT_Float32) dst_ds.SetGeoTransform(geoTrans) dst_ds.SetProjection(projection) # npArray = linear_stretch_3d(npArray) for i in range(1, 65 + 1): dst_ds.GetRasterBand(i).WriteArray(npArray[:, :, i - 1]) dst_ds = None
def run_block(integrator_type): currdir = os.path.split(os.path.realpath(__file__))[0] rt_dir = os.path.join(currdir + '/bin/rt/' + current_rt_program) os.environ['PATH'] = rt_dir + os.pathsep + os.environ['PATH'] excuable = 'lessrt' xml_filename = 'lidar_main.xml' scene_file_path = os.path.join(session.get_scenefile_path(), xml_filename) distFile = os.path.join(session.get_output_dir(), integrator_type) if not os.path.exists(distFile): os.makedirs(distFile) print('make output dir: ' + distFile) for i in os.listdir( os.path.join(session.get_scenefile_path(), 'lidarbatch')): # command = [excuable, '-D', 'batchFile=' + '"' + str(i) + '"', '-o', distFile, scene_file_path] command = 'lessrt -D integratorType="' + integrator_type + '" -D batchFile="' + i + '" -o ' + distFile + ' ' + scene_file_path log('INFO: ', command) subprocess.call(command)
def save_proj_as(oldprojectPath): session.new_proj_indicator() shutil.copytree(combine_file_path(oldprojectPath, input_dir), input_dir) os.mkdir(output_dir) log("Succeed save as: ", os.path.realpath(os.path.curdir))
def generateAtsXmlNF(dart_maket_path, output_xml_path, width, height): log("INFO: Generating atmosphere.") layer_depths, g_params, ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol \ = readParametersFromDartMaketFile(dart_maket_path) total_ext_coeff = ext_coeff_mol + ext_coeff_aerosol total_albedo = weighted_albedo(ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) weightsForPhase = weights_for_phase_function_maximum( ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) sampledBandIndexForEachLayer = getSampledIndexForEachLayer( ext_coeff_mol, ext_coeff_aerosol) f = codecs.open(output_xml_path, "w", "utf-8-sig") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") vertical_offset = -0.00001 # shapeNode = doc.createElement("shape") # root.appendChild(shapeNode) # shapeNode.setAttribute("type","cube") # toWorldNode = doc.createElement("transform") # shapeNode.appendChild(toWorldNode) # toWorldNode.setAttribute("name", "toWorld") # scaleNode = doc.createElement("scale") # toWorldNode.appendChild(scaleNode) # scaleNode.setAttribute("x", str(width * 0.5)) # scaleNode.setAttribute("z", str(height * 0.5)) # scaleNode.setAttribute("y", str(sum(layer_depths) * 0.5)) # total atmosphere height # translateNode = doc.createElement("translate") # toWorldNode.appendChild(translateNode) # translateNode.setAttribute("y", str(sum(layer_depths) * 0.5 + vertical_offset)) mediumNode = doc.createElement("medium") root.appendChild(mediumNode) mediumNode.setAttribute("id", "ats_medium") mediumNode.setAttribute("name", "interior") mediumNode.setAttribute("type", "planeparallel") floatNode = doc.createElement("float") mediumNode.appendChild(floatNode) floatNode.setAttribute("name", "startAltitude") floatNode.setAttribute("value", str(vertical_offset)) strNode = doc.createElement("string") mediumNode.appendChild(strNode) strNode.setAttribute("name", "layerThickness") strNode.setAttribute("value", ",".join([str(t) for t in layer_depths])) layer_index = 1 for i in range(len(layer_depths)): if any(total_ext_coeff[i] > 0): specNode = doc.createElement("spectrum") mediumNode.appendChild(specNode) specNode.setAttribute("name", "singmaT_layer" + str(layer_index)) specNode.setAttribute( "value", ",".join([str(t) for t in total_ext_coeff[i]])) specNode = doc.createElement("spectrum") mediumNode.appendChild(specNode) specNode.setAttribute("name", "albedo_layer" + str(layer_index)) specNode.setAttribute("value", ",".join([str(t) for t in total_albedo[i]])) strNode = doc.createElement("string") mediumNode.appendChild(strNode) strNode.setAttribute("name", "phasefunc_weights_layer" + str(layer_index)) strNode.setAttribute( "value", ",".join([str(t) for t in weightsForPhase[i]])) specNode = doc.createElement("spectrum") mediumNode.appendChild(specNode) specNode.setAttribute("name", "phasefunc_g_value_layer" + str(layer_index)) specNode.setAttribute("value", ",".join([str(t) for t in g_params])) intNode = doc.createElement("integer") mediumNode.appendChild(intNode) intNode.setAttribute( "name", "phasefunc_sampledBandIndex_layer" + str(layer_index)) # intNode.setAttribute("value",str(sampledBandIndexForEachLayer[i])) intNode.setAttribute("value", str(1)) layer_index += 1 xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() log("INFO: Atmosphere generated.")
def terr_generate(config_file_path, terrain_file_prifix=""): log("INFO: Generating terrain...") f = open(config_file_path, 'r') cfg = json.load(f) if cfg["scene"]["terrain"]["terr_file"] == "" and\ cfg["scene"]["terrain"]["terrain_type"] != "PLANE": return f = open( combine_file_path(session.get_scenefile_path(), terrain_file_prifix + terr_scene_file), "w") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") demNode = doc.createElement("shape") root.appendChild(demNode) demNode.setAttribute("id", "terrain") if cfg["scene"]["terrain"]["terrain_type"] == "RASTER": demNode.setAttribute("type", "heightfield") boolNode = doc.createElement("boolean") demNode.appendChild(boolNode) boolNode.setAttribute("name", "shadingNormals") boolNode.setAttribute("value", "false") # textureNode = doc.createElement("texture") # demNode.appendChild(textureNode) # textureNode.setAttribute("type", "bitmap") strNode = doc.createElement("string") demNode.appendChild(strNode) # textureNode.appendChild(strNode) strNode.setAttribute("name", "filename") exr_file_path = combine_file_path( session.get_scenefile_path(), cfg["scene"]["terrain"]["terr_file"] + ".exr") RasterHelper.convert_dem_to_mip_monochromatic_chanel(combine_file_path(session.get_input_dir(),\ cfg["scene"]["terrain"]["terr_file"]), exr_file_path) strNode.setAttribute("value", cfg["scene"]["terrain"]["terr_file"] + ".exr") # floatNode = doc.createElement("float") # demNode.appendChild(floatNode) # floatNode.setAttribute("name", "scale") # floatNode.setAttribute("value", "1.4") transNode = doc.createElement("transform") demNode.appendChild(transNode) transNode.setAttribute("name", "toWorld") rotateNode = doc.createElement("rotate") transNode.appendChild(rotateNode) rotateNode.setAttribute("angle", "-90") rotateNode.setAttribute("x", "1") scaleNode = doc.createElement("scale") transNode.appendChild(scaleNode) scaleNode.setAttribute( "x", str(cfg["scene"]["terrain"]["extent_width"] / 2.0)) scaleNode.setAttribute( "z", str(cfg["scene"]["terrain"]["extent_height"] / 2.0)) if cfg["scene"]["terrain"]["terrain_type"] == "MESH": demNode.setAttribute("type", "obj") strNode = doc.createElement("string") demNode.appendChild(strNode) strNode.setAttribute("name", "filename") strNode.setAttribute("value", cfg["scene"]["terrain"]["terr_file"]) # raster_file = combine_file_path(session.get_input_dir(), cfg["scene"]["terrain"]["terr_file"]) # meshfile = combine_file_path(session.get_scenefile_path(), cfg["scene"]["terrain"]["terr_file"]+".obj") # RasterHelper.Raster2Ojb(raster_file, meshfile) distObjFile = os.path.join(session.get_scenefile_path(), cfg["scene"]["terrain"]["terr_file"]) srcObjFile = os.path.join(session.get_input_dir(), cfg["scene"]["terrain"]["terr_file"]) if os.path.exists(distObjFile): os.remove(distObjFile) from shutil import copyfile copyfile(srcObjFile, distObjFile) facenormalNode = doc.createElement("boolean") demNode.appendChild(facenormalNode) facenormalNode.setAttribute("name", "faceNormals") facenormalNode.setAttribute("value", "true") if cfg["scene"]["terrain"]["terrain_type"] == "PLANE": demNode.setAttribute("type", "rectangle") transNode = doc.createElement("transform") demNode.appendChild(transNode) transNode.setAttribute("name", "toWorld") rotateNode = doc.createElement("rotate") transNode.appendChild(rotateNode) rotateNode.setAttribute("angle", "-90") rotateNode.setAttribute("x", "1") scaleNode = doc.createElement("scale") transNode.appendChild(scaleNode) scaleNode.setAttribute( "x", str(cfg["scene"]["terrain"]["extent_width"] / 2.0)) scaleNode.setAttribute( "z", str(cfg["scene"]["terrain"]["extent_height"] / 2.0)) bsdf = doc.createElement("bsdf") demNode.appendChild(bsdf) if cfg["scene"]["terrain"]["terrBRDFType"] == "Soilspect": bsdf.setAttribute("type", "soilspect") else: bsdf.setAttribute("type", "diffuse") # for thermal if cfg["sensor"]["thermal_radiation"]: emitter_node = doc.createElement("emitter") demNode.appendChild(emitter_node) emitter_node.setAttribute("type", "planck") tNode = doc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "temperature") terrTempStr = cfg["scene"]["temperature_properties"][ cfg["scene"]["terrain"]["temperature"]] terrArr = terrTempStr.split(":") tNode.setAttribute("value", terrArr[0]) tNode = doc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "deltaTemperature") tNode.setAttribute("value", terrArr[1]) arrs = cfg["sensor"]["bands"].split(",") wavelengths = [] for wl in arrs: arr = wl.split(":") wavelengths.append(arr[0]) waveNode = doc.createElement("spectrum") emitter_node.appendChild(waveNode) waveNode.setAttribute("name", "wavelengths") waveNode.setAttribute("value", ",".join(wavelengths)) ft = open( os.path.join(session.get_output_dir(), wavelength_file_for_thermal), 'w') ft.write(",".join(wavelengths)) ft.close() v_node = doc.createElement("vector") emitter_node.appendChild(v_node) v_node.setAttribute("name", "direction") theta = float( cfg["illumination"]["sun"]["sun_zenith"]) / 180.0 * np.pi phi = (float(cfg["illumination"]["sun"]["sun_azimuth"]) - 90) / 180.0 * np.pi x = np.sin(theta) * np.cos(phi) z = np.sin(theta) * np.sin(phi) y = -np.cos(theta) v_node.setAttribute("x", str(x)) v_node.setAttribute("y", str(y)) v_node.setAttribute("z", str(z)) # from Utils import emittion_spectral # spectrumNode = doc.createElement("spectrum") # emitter_node.appendChild(spectrumNode) # spectrumNode.setAttribute("name","radiance") # emit_spectral = emittion_spectral(float(cfg["scene"]["temperature_properties"][cfg["scene"]["terrain"]["temperature"]]), # cfg["sensor"]["bands"]) # spectrumNode.setAttribute("value",emit_spectral) if "landcover" not in cfg["scene"]["terrain"]: if cfg["scene"]["terrain"]["terrBRDFType"] == "Lambertian": reflectancenode = doc.createElement("spectrum") bsdf.appendChild(reflectancenode) reflectancenode.setAttribute("name", "reflectance") factor = cfg["scene"]["terrain"]["optical_scale"] defined_optical_name = cfg["scene"]["terrain"]["optical"] optical_name_or_list = cfg["scene"]["optical_properties"][ defined_optical_name]["value"] if optical_name_or_list == "": log("No optical property of ground detected.") sys.exit(0) reflectancenode.setAttribute( "value", optical_name_or_list.split(";")[0]) elif cfg["scene"]["terrain"]["terrBRDFType"] == "Soilspect": spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "albedo") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["albedo"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "c1") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["c1"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "c2") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["c2"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "c3") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["c3"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "c4") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["c4"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "h1") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["h1"]) spec = doc.createElement("spectrum") bsdf.appendChild(spec) spec.setAttribute("name", "h2") spec.setAttribute( "value", cfg["scene"]["terrain"]["soilSpectParams"]["h2"]) elif cfg["scene"]["terrain"]["terrBRDFType"] == "Land Albedo Map": textureNode = doc.createElement("texture") bsdf.appendChild(textureNode) textureNode.setAttribute("type", "bitmap") textureNode.setAttribute("name", "reflectance") filterTypeNode = doc.createElement("string") textureNode.appendChild(filterTypeNode) filterTypeNode.setAttribute("name", "filterType") filterTypeNode.setAttribute("value", "nearest") strNode = doc.createElement("string") textureNode.appendChild(strNode) strNode.setAttribute("name", "filename") strNode.setAttribute("value", "landalbedo.exr") boolNode = doc.createElement("boolean") textureNode.appendChild(boolNode) boolNode.setAttribute("name", "cache") boolNode.setAttribute("value", "false") from create_envmap import createLandAlbedoMap log("INFO: Creating land albedo map...") createLandAlbedoMap( len(cfg["sensor"]["bands"].split(",")), os.path.join(session.get_input_dir(), cfg["scene"]["terrain"]["landalbedo"]), os.path.join(session.get_scenefile_path(), "landalbedo.exr")) else: textureNode = doc.createElement("texture") bsdf.appendChild(textureNode) textureNode.setAttribute("type", "bitmap") textureNode.setAttribute("name", "reflectance") filterTypeNode = doc.createElement("string") textureNode.appendChild(filterTypeNode) filterTypeNode.setAttribute("name", "filterType") filterTypeNode.setAttribute("value", "nearest") strNode = doc.createElement("string") textureNode.appendChild(strNode) strNode.setAttribute("name", "filename") strNode.setAttribute("value", "landcover.exr") boolNode = doc.createElement("boolean") textureNode.appendChild(boolNode) boolNode.setAttribute("name", "cache") boolNode.setAttribute("value", "false") from create_envmap import createLandcoverMap, createLandcoverMap_trans log("INFO: Creating land cover map...") createLandcoverMap( os.path.join(session.get_input_dir(), imported_landcover_raster_name), os.path.join(session.get_scenefile_path(), "landcover.exr"), os.path.join(session.get_input_dir(), "landcover.txt"), cfg["scene"]["optical_properties"]["value"], len(cfg["sensor"]["bands"].split(","))) # createLandcoverMap_trans(os.path.join(session.get_input_dir(), imported_landcover_raster_name), # os.path.join(session.get_scenefile_path(), "landtrans.exr"), # os.path.join(session.get_input_dir(), "landcover.txt"), # cfg["scene"]["optical_properties"], # len(cfg["sensor"]["bands"].split(","))) xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() if terrain_file_prifix == "": log("INFO: Terrain generated.")
def forest_generate_according_tree_pos_file(config_file_path, forest_file_name, linestart, lineend, forest_prifix=""): import mitsuba from mitsuba.core import Vector, Point, Ray, Thread from mitsuba.render import SceneHandler from mitsuba.render import RenderQueue, RenderJob from mitsuba.render import Scene from mitsuba.render import Intersection f = open(config_file_path, 'r') cfg = json.load(f) tree_pos = combine_file_path(session.get_input_dir(), cfg["scene"]["forest"]["tree_pos_file"]) if cfg["scene"]["forest"]["tree_pos_file"] == "" or ( not os.path.exists(tree_pos)): return # 保存场景中树的位置 forest*.xml # f = open(os.path.join(session.get_scenefile_path(),forest_file_name),'w') f = codecs.open( os.path.join(session.get_scenefile_path(), forest_file_name), "w", "utf-8-sig") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") #读取地形数据 计算每个树的高程 if cfg["scene"]["terrain"]["terrain_type"] != "PLANE" and cfg["scene"][ "terrain"]["terrain_type"] == "RASTER": demfile = combine_file_path(session.get_input_dir(), cfg["scene"]["terrain"]["terr_file"]) img_w, img_h, dem_arr = RasterHelper.read_dem_as_array(demfile) dem_arr = dem_arr - dem_arr.min() #读取object boundingbox 数据 bound_path = os.path.join(session.get_input_dir(), obj_bounding_box_file) if os.path.exists(bound_path): fobj = open(bound_path) bound_dict = dict() for line in fobj: arr = line.split(":") objName = arr[0] arr = list(map(lambda x: float(x), arr[1].split(" "))) bound_dict[objName] = [ arr[3] - arr[0], arr[4] - arr[1], arr[5] - arr[2] ] scenepath = session.get_scenefile_path() # if "Windows" in platform.system(): # scenepath = str(scenepath.replace('\\', '\\\\')) #得到高程信息 通过光线跟踪的方法精确得到高程信息 fileResolver = Thread.getThread().getFileResolver() logger = Thread.getThread().getLogger() logger.clearAppenders() fileResolver.appendPath(str(scenepath)) # 由于batch模式不会改变地形几何结构,因此在用地形打点计算树木的高程时,用第一个terrain文件即可,所以加上了_0_ # if(forest_prifix != ""): # forest_prifix = forest_prifix[0:len(forest_prifix)-1] +"_0_" scene = SceneHandler.loadScene( fileResolver.resolve(str(forest_prifix + terr_scene_file))) # scene = SceneHandler.loadScene(fileResolver.resolve(r"E:\Research\20-LESS\RealScene\SimProj\calLAI\Parameters\_scenefile\terrain1.xml")) scene.configure() scene.initialize() tf = open(tree_pos) hidden_objects = SceneGenerate.get_hidded_objects() #创建一个虚拟根节点,最后再删除 treeIdx = 0 for line in tf: if treeIdx >= linestart and treeIdx <= lineend: arr = line.replace("\n", "").strip().split(" ") objectName = arr[0] if objectName in hidden_objects: continue shapenode = doc.createElement("shape") root.appendChild(shapenode) shapenode.setAttribute("type", "instance") refnode = doc.createElement("ref") shapenode.appendChild(refnode) refnode.setAttribute("id", objectName) trnode = doc.createElement("transform") shapenode.appendChild(trnode) trnode.setAttribute("name", "toWorld") if len(arr) == 6: # fit with scale_node = doc.createElement("scale") trnode.appendChild(scale_node) scale_node.setAttribute( "x", str(float(arr[4]) / bound_dict[objectName][0])) scale_node.setAttribute( "z", str(float(arr[4]) / bound_dict[objectName][0])) scale_node.setAttribute( "y", str(float(arr[5]) / bound_dict[objectName][1])) if len(arr) == 5: # for rotation of the tree angle = arr[len(arr) - 1] rotatenode = doc.createElement("rotate") trnode.appendChild(rotatenode) rotatenode.setAttribute("y", '1') rotatenode.setAttribute("angle", angle) translatenode = doc.createElement("translate") trnode.appendChild(translatenode) x = float(arr[1]) y = float(arr[2]) z = float(arr[3]) xScale = cfg["scene"]["terrain"]["extent_width"] zScale = cfg["scene"]["terrain"]["extent_height"] # treeX = xScale - x * (2 * xScale) / float(img_w) # treeZ = zScale - y * (2 * zScale) / float(img_h) treeX = 0.5 * xScale - x treeZ = 0.5 * zScale - y translatenode.setAttribute("x", str(treeX)) translatenode.setAttribute("z", str(treeZ)) if cfg["scene"]["terrain"]["terrain_type"] != "PLANE": ray = Ray() ray.setOrigin(Point(treeX, 9999, treeZ)) ray.setDirection(Vector(0, -1, 0)) its = scene.rayIntersect(ray) if not its is None: translatenode.setAttribute("y", str(its.p[1] + z)) # translatenode.setAttribute("y", str(z)) else: # log("warning: precise height not found.") if cfg["scene"]["terrain"]["terrain_type"] == "RASTER": im_r = int((y / float(zScale)) * img_h) im_c = int((x / float(xScale)) * img_w) if im_r >= img_h: im_r = img_h - 1 if im_c >= img_w: im_c = img_w - 1 translatenode.setAttribute( "y", str(dem_arr[im_r][im_c] + z)) else: translatenode.setAttribute("y", str(z)) else: translatenode.setAttribute("y", str(z)) treeIdx += 1 xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() log("INFO: Objects and positions generated.")
def generate_objects_file(config_file_path, obj_file_prifix=""): f = open(config_file_path, 'r') cfg = json.load(f) objects_file_path = combine_file_path( session.get_input_dir(), cfg["scene"]["forest"]["objects_file"]) if cfg["scene"]["forest"]["objects_file"] == "" or ( not os.path.exists(objects_file_path)): log("INFO: No objects defined.") return # objf = open(os.path.join(session.get_scenefile_path(), obj_file_prifix + object_scene_file), 'w') objf = codecs.open( os.path.join(session.get_scenefile_path(), obj_file_prifix + object_scene_file), "w", "utf-8-sig") objdoc = minidom.Document() objroot = objdoc.createElement("scene") objdoc.appendChild(objroot) objroot.setAttribute("version", "0.5.0") hidden_objects = SceneGenerate.get_hidded_objects() tf = open(objects_file_path) opticalSet = set() object_optical = [] for line in tf: if line != "": arr = line.replace("\n", "").split(" ") object_name = arr[0] if object_name not in hidden_objects: object_optical.append(arr) for i in range(1, len(arr), 4): opticalSet.add( arr[i + 1]) # add all spectral properties to set opticalSet = list(opticalSet) for i in range(0, len(opticalSet)): defined_op = cfg["scene"]["optical_properties"][ opticalSet[i]]["value"] arr = defined_op.split(";") if len(arr) != 3: log("Error while setting optical properties.") if check_if_string_is_zero_and_comma( arr[1]) and check_if_string_is_zero_and_comma(arr[2]): # oneside bsdf = objdoc.createElement("bsdf") bsdf.setAttribute("id", opticalSet[i]) objroot.appendChild(bsdf) bsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") bsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[0]) else: # twoside bsdfnode = objdoc.createElement("bsdf") objroot.appendChild(bsdfnode) bsdfnode.setAttribute("id", opticalSet[i]) bsdfnode.setAttribute("type", "mixturebsdf") bnode = objdoc.createElement("boolean") bsdfnode.appendChild(bnode) bnode.setAttribute("name", "ensureEnergyConservation") bnode.setAttribute("value", "false") strnode = objdoc.createElement("string") bsdfnode.appendChild(strnode) strnode.setAttribute("name", "weights") strnode.setAttribute("value", "1,1") twobsdf = objdoc.createElement("bsdf") bsdfnode.appendChild(twobsdf) twobsdf.setAttribute("type", "twosided") diffbsdf = objdoc.createElement("bsdf") twobsdf.appendChild(diffbsdf) diffbsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") diffbsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[0]) diffbsdf = objdoc.createElement("bsdf") twobsdf.appendChild(diffbsdf) diffbsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") diffbsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[1]) transnode = objdoc.createElement("bsdf") bsdfnode.appendChild(transnode) transnode.setAttribute("type", "difftrans") specnode = objdoc.createElement("spectrum") transnode.appendChild(specnode) specnode.setAttribute("name", "transmittance") specnode.setAttribute("value", arr[2]) for i in range(0, len(object_optical)): rowdata = object_optical[i] objectName = rowdata[0] #创建group shapenode = objdoc.createElement("shape") objroot.appendChild(shapenode) shapenode.setAttribute("id", objectName) shapenode.setAttribute("type", "shapegroup") for j in range(1, len(rowdata), 4): compnentName = rowdata[j] opticalName = rowdata[j + 1] temperatureName = rowdata[j + 2] subshapnode = objdoc.createElement("shape") shapenode.appendChild(subshapnode) subshapnode.setAttribute("type", "serialized") subshapnode.setAttribute("id", os.path.splitext(compnentName)[0]) strnode = objdoc.createElement("string") subshapnode.appendChild(strnode) strnode.setAttribute("name", "filename") # import chardet # convert to serizlized # the string reading from object.txt, which is produced by Java, is in gbk encoding # objfile = os.path.join(session.get_input_dir(), compnentName.encode("gbk").decode("utf-8")) objfile = os.path.join(session.get_input_dir(), compnentName) convert_obj_2_serialized( objfile, session.get_scenefile_path(), cfg["scene"]["forest"]["CacheOBJFile"]) strnode.setAttribute( "value", os.path.splitext(compnentName)[0] + ".serialized") refnode = objdoc.createElement("ref") subshapnode.appendChild(refnode) refnode.setAttribute("id", opticalName) # using face normal boolNode = objdoc.createElement("boolean") subshapnode.appendChild(boolNode) boolNode.setAttribute("name", "faceNormals") boolNode.setAttribute("value", "true") # for thermal if cfg["sensor"]["thermal_radiation"]: emitter_node = objdoc.createElement("emitter") subshapnode.appendChild(emitter_node) emitter_node.setAttribute("type", "planck") tNode = objdoc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "temperature") tmperatureStr = cfg["scene"]["temperature_properties"][ temperatureName] tmparr = tmperatureStr.split(":") tNode.setAttribute("value", tmparr[0]) tNode = objdoc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "deltaTemperature") tNode.setAttribute("value", tmparr[1]) arrs = cfg["sensor"]["bands"].split(",") wavelengths = [] for wl in arrs: arr = wl.split(":") wavelengths.append(arr[0]) waveNode = objdoc.createElement("spectrum") emitter_node.appendChild(waveNode) waveNode.setAttribute("name", "wavelengths") waveNode.setAttribute("value", ",".join(wavelengths)) v_node = objdoc.createElement("vector") emitter_node.appendChild(v_node) v_node.setAttribute("name", "direction") theta = float(cfg["illumination"]["sun"] ["sun_zenith"]) / 180.0 * np.pi phi = (float(cfg["illumination"]["sun"]["sun_azimuth"]) - 90) / 180.0 * np.pi x = np.sin(theta) * np.cos(phi) z = np.sin(theta) * np.sin(phi) y = -np.cos(theta) v_node.setAttribute("x", str(x)) v_node.setAttribute("y", str(y)) v_node.setAttribute("z", str(z)) # from Utils import emittion_spectral # emitter_node = objdoc.createElement("emitter") # subshapnode.appendChild(emitter_node) # emitter_node.setAttribute("type", "area") # spectrumNode = objdoc.createElement("spectrum") # emitter_node.appendChild(spectrumNode) # spectrumNode.setAttribute("name", "radiance") # emit_spectral = emittion_spectral( # float(cfg["scene"]["temperature_properties"][temperatureName]), # cfg["sensor"]["bands"]) # spectrumNode.setAttribute("value", emit_spectral) xm = objdoc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') objf.write(xm) objf.close()
def generate_objects_file(config_file_path, obj_file_prifix=""): f = open(config_file_path, 'r') cfg = json.load(f) objects_file_path = combine_file_path( session.get_input_dir(), cfg["scene"]["forest"]["objects_file"]) if cfg["scene"]["forest"]["objects_file"] == "" or ( not os.path.exists(objects_file_path)): log("INFO: No objects defined.") return # objf = open(os.path.join(session.get_scenefile_path(), obj_file_prifix + object_scene_file), 'w') objf = codecs.open( os.path.join(session.get_scenefile_path(), obj_file_prifix + object_scene_file), "w", "utf-8-sig") objdoc = minidom.Document() objroot = objdoc.createElement("scene") objdoc.appendChild(objroot) objroot.setAttribute("version", "0.5.0") hidden_objects = SceneGenerate.get_hidded_objects() tf = open(objects_file_path) opticalSet = set() object_optical = [] for line in tf: if line != "": arr = line.replace("\n", "").split(" ") object_name = arr[0] if object_name not in hidden_objects: object_optical.append(arr) for i in range(1, len(arr), 8): opticalSet.add( arr[i + 1]) # add all spectral properties to set opticalSet = list(opticalSet) optical_map = dict() # store the optical name - value pairs for i in range(0, len(opticalSet)): defined_op = cfg["scene"]["optical_properties"][ opticalSet[i]]["value"] op_type = cfg["scene"]["optical_properties"][opticalSet[i]]["Type"] if op_type == 2: # using prospect model ProspectDParams = cfg["scene"]["optical_properties"][ opticalSet[i]]["ProspectDParams"] tmparr = cfg["sensor"]["bands"].split(",") wls = [] for tmp in tmparr: wl = tmp.split(":")[0] wls.append(wl) (ref, trans) = prospect5AndD( ",".join(wls), ProspectDParams["isProsect5"], ProspectDParams["N"], ProspectDParams["Car"], ProspectDParams["BP"], ProspectDParams["Cm"], ProspectDParams["Cab"], ProspectDParams["Anth"], ProspectDParams["Cw"]) defined_op = ref + ";" + ref + ";" + trans optical_map[opticalSet[i]] = defined_op arr = defined_op.split(";") if len(arr) != 3: log("Error while setting optical properties.") if check_if_string_is_zero_and_comma( arr[1]) and check_if_string_is_zero_and_comma(arr[2]): # oneside bsdf = objdoc.createElement("bsdf") bsdf.setAttribute("id", opticalSet[i]) objroot.appendChild(bsdf) bsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") bsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[0]) else: # twoside bsdfnode = objdoc.createElement("bsdf") objroot.appendChild(bsdfnode) bsdfnode.setAttribute("id", opticalSet[i]) bsdfnode.setAttribute("type", "mixturebsdf") bnode = objdoc.createElement("boolean") bsdfnode.appendChild(bnode) bnode.setAttribute("name", "ensureEnergyConservation") bnode.setAttribute("value", "false") strnode = objdoc.createElement("string") bsdfnode.appendChild(strnode) strnode.setAttribute("name", "weights") strnode.setAttribute("value", "1,1") twobsdf = objdoc.createElement("bsdf") bsdfnode.appendChild(twobsdf) twobsdf.setAttribute("type", "twosided") diffbsdf = objdoc.createElement("bsdf") twobsdf.appendChild(diffbsdf) diffbsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") diffbsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[0]) diffbsdf = objdoc.createElement("bsdf") twobsdf.appendChild(diffbsdf) diffbsdf.setAttribute("type", "diffuse") specnode = objdoc.createElement("spectrum") diffbsdf.appendChild(specnode) specnode.setAttribute("name", "reflectance") specnode.setAttribute("value", arr[1]) transnode = objdoc.createElement("bsdf") bsdfnode.appendChild(transnode) transnode.setAttribute("type", "difftrans") specnode = objdoc.createElement("spectrum") transnode.appendChild(specnode) specnode.setAttribute("name", "transmittance") specnode.setAttribute("value", arr[2]) for i in range(0, len(object_optical)): rowdata = object_optical[i] objectName = rowdata[0] # 创建group shapenode = objdoc.createElement("shape") objroot.appendChild(shapenode) shapenode.setAttribute("id", objectName) shapenode.setAttribute("type", "shapegroup") for j in range(1, len(rowdata), 8): compnentName = rowdata[j] opticalName = rowdata[j + 1] temperatureName = rowdata[j + 2] isMedium = True if rowdata[j + 4] == "true" else False subshapnode = objdoc.createElement("shape") shapenode.appendChild(subshapnode) subshapnode.setAttribute("type", "serialized") subshapnode.setAttribute("id", os.path.splitext(compnentName)[0]) strnode = objdoc.createElement("string") subshapnode.appendChild(strnode) strnode.setAttribute("name", "filename") # import chardet # convert to serizlized # the string reading from object.txt, which is produced by Java, is in gbk encoding # objfile = os.path.join(session.get_input_dir(), compnentName.encode("gbk").decode("utf-8")) objfile = os.path.join(session.get_input_dir(), compnentName) convert_obj_2_serialized( objfile, session.get_scenefile_path(), cfg["scene"]["forest"]["CacheOBJFile"]) strnode.setAttribute( "value", os.path.splitext(compnentName)[0] + ".serialized") if not isMedium: # if the shape is not a medium refnode = objdoc.createElement("ref") subshapnode.appendChild(refnode) refnode.setAttribute("id", opticalName) # using face normal boolNode = objdoc.createElement("boolean") subshapnode.appendChild(boolNode) boolNode.setAttribute("name", "faceNormals") boolNode.setAttribute("value", "true") else: # The shape is a medium mediumnode = objdoc.createElement("medium") subshapnode.appendChild(mediumnode) mediumnode.setAttribute("name", "interior") mediumnode.setAttribute("type", "vegmedium") define_op = optical_map[opticalName] arr = define_op.split(";") # albedo albedo = list( map(lambda xx, yy: str(float(xx) + float(yy)), arr[0].split(","), arr[2].split(","))) albedonode = objdoc.createElement("spectrum") mediumnode.appendChild(albedonode) albedonode.setAttribute("name", "singleScatteringAlbedo") albedonode.setAttribute("value", ",".join(albedo)) densitynode = objdoc.createElement("float") mediumnode.appendChild(densitynode) densitynode.setAttribute("name", "leafAreaDensity") densitynode.setAttribute("value", rowdata[j + 5]) ladphasenode = objdoc.createElement("phase") mediumnode.appendChild(ladphasenode) ladphasenode.setAttribute("type", "vegphase") ladnode = objdoc.createElement("string") ladphasenode.appendChild(ladnode) ladnode.setAttribute("name", "ladtype") ladnode.setAttribute("value", rowdata[j + 6]) hotspotnode = objdoc.createElement("float") ladphasenode.appendChild(hotspotnode) hotspotnode.setAttribute("name", "hotspotFactor") hotspotnode.setAttribute("value", rowdata[j + 7]) # for thermal if cfg["sensor"]["thermal_radiation"]: emitter_node = objdoc.createElement("emitter") subshapnode.appendChild(emitter_node) emitter_node.setAttribute("type", "planck") tNode = objdoc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "temperature") tmperatureStr = cfg["scene"]["temperature_properties"][ temperatureName] tmparr = tmperatureStr.split(":") tNode.setAttribute("value", tmparr[0]) tNode = objdoc.createElement("float") emitter_node.appendChild(tNode) tNode.setAttribute("name", "deltaTemperature") tNode.setAttribute("value", tmparr[1]) arrs = cfg["sensor"]["bands"].split(",") wavelengths = [] for wl in arrs: arr = wl.split(":") wavelengths.append(arr[0]) waveNode = objdoc.createElement("spectrum") emitter_node.appendChild(waveNode) waveNode.setAttribute("name", "wavelengths") waveNode.setAttribute("value", ",".join(wavelengths)) v_node = objdoc.createElement("vector") emitter_node.appendChild(v_node) v_node.setAttribute("name", "direction") theta = float(cfg["illumination"]["sun"] ["sun_zenith"]) / 180.0 * np.pi phi = (float(cfg["illumination"]["sun"]["sun_azimuth"]) - 90) / 180.0 * np.pi x = np.sin(theta) * np.cos(phi) z = np.sin(theta) * np.sin(phi) y = -np.cos(theta) v_node.setAttribute("x", str(x)) v_node.setAttribute("y", str(y)) v_node.setAttribute("z", str(z)) # from Utils import emittion_spectral # emitter_node = objdoc.createElement("emitter") # subshapnode.appendChild(emitter_node) # emitter_node.setAttribute("type", "area") # spectrumNode = objdoc.createElement("spectrum") # emitter_node.appendChild(spectrumNode) # spectrumNode.setAttribute("name", "radiance") # emit_spectral = emittion_spectral( # float(cfg["scene"]["temperature_properties"][temperatureName]), # cfg["sensor"]["bands"]) # spectrumNode.setAttribute("value", emit_spectral) xm = objdoc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') objf.write(xm) objf.close()
def checkproj(): curr_dir = os.getcwd() check_file = curr_dir + os.sep + less_identifier if not os.path.exists(check_file): log("This directory is not a valid simulation") sys.exit(0)
else: data = data[:, :, 0:5] bandlist = [] RasterHelper.saveToHdr_no_transform( data, distFile + "_4Components", bandlist, output_format) os.remove(distFile + "_4Components.npy") def clear_json_file(self): self.readParameterFileList() for filename in self.parameter_file_list: filepath = os.path.join(session.get_input_dir(), filename) os.remove(filepath) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument('--batchPath', help="Batch file Path.") args = parser.parse_args() if args.batchPath: session.checkproj() cfgfile = session.get_config_file() bt = BatchGenAndRun(cfgfile, args.batchPath) # bt.createFolder() log("INFO: Begin to run Batch.") bt.parse_seq() bt.generate_xml_from_all_seq() bt.run_seq() bt.clear_json_file()
SceneGenerate.terr_generate(cfgfile) clear_input("forest") SceneGenerate.generate_objects_file(cfgfile) SceneGenerate.forest_generate(cfgfile) if gvalue in ("t", 'terrain'): SceneGenerate.write_range_num_for_RT(cfgfile) clear_input("terrain") SceneGenerate.terr_generate(cfgfile) if gvalue in ("f", "forest"): SceneGenerate.write_range_num_for_RT(cfgfile) clear_input("forest") SceneGenerate.generate_objects_file(cfgfile) SceneGenerate.forest_generate(cfgfile) if gvalue in ("m", "m3d"): SceneGenerate.write_range_num_for_RT(cfgfile) clear_input("terrain") SceneGenerate.terr_generate(cfgfile) threeDView.forest_generate_according_tree_pos_file_for3d(cfgfile) if args.version: log("LESS Simulation Program(V1.0), Developed by Jianbo Qi, Beijing Normal University." ) if args.newseq is not None: value = args.newseq session.checkproj() new_sequencer(value) if args.saveas is not None: oldproj_path = args.saveas save_proj_as(oldproj_path)
for tree in self.forest_data: f.write("o " + tree + "_branch_stem.obj branch_reflectance " + tree + "_foliage.obj leaf_ref_trans\n") index = 0 for tree in self.forest_data: pos_data, rotation_data = self.forest_data[tree] for i in range(0, len(rotation_data)): f.write("i %.5f %.5f %d %.5f\n" % (pos_data[i][0], args.Y - pos_data[i][1], index, rotation_data[i])) index += 1 f.close() if args.phase == "RAMI-IV" and args.sceneID == "HET07_JPS_SUM": log(args.phase, args.sceneID) distDir = args.distDir currdir = os.path.split(os.path.realpath(__file__))[0] template_folder = combine_file_path_multi(currdir, "template", "RAMI", "RAMI-IV", "HET07_JPS_SUM") shoot_file = combine_file_path(template_folder, "PISY_shoot.def") needle = Needle() needle.toObj(r"E:\Coding\Mitsuba\simulations\RAMI4new\needle.obj") shoot = Shoot(needle) shoot.generate_twig_from_file(shoot_file) shoot.toObj(r"E:\Coding\Mitsuba\simulations\RAMI4new\shoot.obj") # leaf_file = combine_file_path(template_folder, "BEPE_leaf.def") # foliage_file = combine_file_path(template_folder, "BEPE_foliage.dat") # stem_file = combine_file_path(template_folder, "BEPE_stem.dat") # branch_file = combine_file_path(template_folder, "BEPE_branches.dat")
def generateAtsXmlNFTwoStepMode(dart_maket_path, output_xml_path): log("INFO: Generating atmosphere.") layer_depths, g_params, ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol \ = readParametersFromDartMaketFile(dart_maket_path) total_ext_coeff = ext_coeff_mol + ext_coeff_aerosol total_albedo = weighted_albedo(ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) weightsForPhase = weights_for_phase_function_maximum( ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) f = codecs.open(output_xml_path, "w", "utf-8-sig") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") vertical_offset = -0.00001 mediumNode = doc.createElement("medium") root.appendChild(mediumNode) mediumNode.setAttribute("id", "ats_medium") mediumNode.setAttribute("name", "interior") mediumNode.setAttribute("type", "planeparallel") floatNode = doc.createElement("float") mediumNode.appendChild(floatNode) floatNode.setAttribute("name", "startAltitude") floatNode.setAttribute("value", str(vertical_offset)) strNode = doc.createElement("string") mediumNode.appendChild(strNode) strNode.setAttribute("name", "layerThickness") strNode.setAttribute("value", ",".join([str(t) for t in layer_depths])) layer_index = 1 for i in range(len(layer_depths)): if any(total_ext_coeff[i] > 0): specNode = doc.createElement("spectrum") mediumNode.appendChild(specNode) specNode.setAttribute("name", "singmaT_layer" + str(layer_index)) specNode.setAttribute( "value", ",".join([str(t) for t in total_ext_coeff[i]])) specNode = doc.createElement("spectrum") mediumNode.appendChild(specNode) specNode.setAttribute("name", "albedo_layer" + str(layer_index)) specNode.setAttribute("value", ",".join([str(t) for t in total_albedo[i]])) strNode = doc.createElement("string") mediumNode.appendChild(strNode) strNode.setAttribute("name", "phasefunc_weights_layer" + str(layer_index)) strNode.setAttribute( "value", ",".join([str(t) for t in weightsForPhase[i]])) floatNode = doc.createElement("float") mediumNode.appendChild(floatNode) floatNode.setAttribute( "name", "phasefunc_g_value_layer" + str(layer_index)) floatNode.setAttribute("value", str(g_params.max())) layer_index += 1 # ingegrator Node integratorNode = doc.createElement("integrator") root.appendChild(integratorNode) integratorNode.setAttribute("type", "volpath_simple") integerNode = doc.createElement("integer") integratorNode.appendChild(integerNode) integerNode.setAttribute("name", "maxDepth") integerNode.setAttribute("value", "-1") # sensor sensorNode = doc.createElement("sensor") root.appendChild(sensorNode) sensorNode.setAttribute("type", "spherical") xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() log("INFO: Atmosphere generated.")
parser.add_argument('-t', '--type', help="Product Type.", type=str) parser.add_argument('-f', '--file', help="info filename.", type=str) args = parser.parse_args() # processing thermal products if args.type in ("T", "BT", "thermal"): # read wavelengths ft = open( os.path.join(session.get_output_dir(), wavelength_file_for_thermal)) wavelengths = list(map(lambda x: float(x), ft.readline().split(","))) ft.close() seq_info_files = glob.glob( os.path.join(session.get_output_dir(), "*" + BATCH_INFO_FILE)) for seq_file in seq_info_files: seq_name = os.path.splitext(os.path.basename(seq_file))[0].rsplit( "_", 1)[0] log("INFO: Processing Batch: " + seq_name) f = open(seq_file) fbt = open( os.path.join(session.get_output_dir(), seq_name + "_BT.txt"), 'w') for line in f: arr = line.strip().split() radiance_file = arr[0] # 实际上为当个模拟的名称 radiance_path = os.path.join(session.get_output_dir(), radiance_file) meanBTs = bt_single_img_processing(radiance_path, wavelengths) fbt.write(radiance_file + " ") for i in range(0, len(meanBTs)): fbt.write("%.5f " % meanBTs[i]) fbt.write("\n") fbt.close() f.close()
def generateAtsXml(dart_maket_path, output_xml_path, width, height): log("INFO: Generating atmosphere.") layer_depths, g_params, ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol\ = readParametersFromDartMaketFile(dart_maket_path) total_ext_coeff = ext_coeff_mol + ext_coeff_aerosol total_albedo = weighted_albedo(ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) weightsForPhase = weights_for_phase_function(ext_coeff_mol, single_albedo_mol, ext_coeff_aerosol, single_albedo_aerosol) f = codecs.open(output_xml_path, "w", "utf-8-sig") doc = minidom.Document() root = doc.createElement("scene") doc.appendChild(root) root.setAttribute("version", "0.5.0") layer_bottom_height = [0] vertical_offset = 2 for i in range(1, len(layer_depths)): bottom_height = sum(layer_depths[0:i]) layer_bottom_height.append(bottom_height) for i in range(len(layer_depths)): shapeNode = doc.createElement("shape") root.appendChild(shapeNode) shapeNode.setAttribute("type", "cube") toWorldNode = doc.createElement("transform") shapeNode.appendChild(toWorldNode) toWorldNode.setAttribute("name", "toWorld") scaleNode = doc.createElement("scale") toWorldNode.appendChild(scaleNode) scaleNode.setAttribute("x", str(width * 0.5)) scaleNode.setAttribute("z", str(height * 0.5)) scaleNode.setAttribute("y", str(layer_depths[i] * 0.5 - 0.1)) translateNode = doc.createElement("translate") toWorldNode.appendChild(translateNode) translateNode.setAttribute( "y", str(layer_bottom_height[i] + layer_depths[i] * 0.5 + vertical_offset)) mediumNode = doc.createElement("medium") shapeNode.appendChild(mediumNode) mediumNode.setAttribute("name", "interior") mediumNode.setAttribute("type", "homogeneous") spectrumNode = doc.createElement("spectrum") mediumNode.appendChild(spectrumNode) spectrumNode.setAttribute("name", "sigmaT") spectrumNode.setAttribute( "value", ",".join([str(t) for t in total_ext_coeff[i]])) spectrumNode = doc.createElement("spectrum") mediumNode.appendChild(spectrumNode) spectrumNode.setAttribute("name", "albedo") spectrumNode.setAttribute("value", ",".join([str(t) for t in total_albedo[i]])) phaseNode = doc.createElement("phase") mediumNode.appendChild(phaseNode) phaseNode.setAttribute("type", "mixturephase") weightsNode = doc.createElement("string") phaseNode.appendChild(weightsNode) weightsNode.setAttribute("name", "weights") weightsNode.setAttribute( "value", ",".join([str(t) for t in weightsForPhase[i]])) rayleighNode = doc.createElement("phase") phaseNode.appendChild(rayleighNode) rayleighNode.setAttribute("type", "rayleigh") hgNode = doc.createElement("phase") phaseNode.appendChild(hgNode) hgNode.setAttribute("type", "hg") floatNode = doc.createElement("float") hgNode.appendChild(floatNode) floatNode.setAttribute("name", "g") floatNode.setAttribute("value", str(g_params.mean())) xm = doc.toprettyxml() # xm = xm.replace('<?xml version="1.0" ?>', '') f.write(xm) f.close() log("INFO: Atmosphere generated.")