예제 #1
0
def get_stats_by_geom(filename, poly):
    inFile = File(filename, mode="r")
    results = spatial.las_within(inFile, poly["rings"], ["z"])
    inFile.close()
    stats = spatial.las_statistics(results["points"])
    json = js.dumps(stats)
    return json
예제 #2
0
def read_files(files, srs, group_name):
    """ Open a .las file and extract information from header block.
    Then add information to a record in the database. """
    for las_file in files:
        las = File(las_file.file.name, mode='r')
        lidar_obj = LidarFiles()
        lidar_obj.name = las_file
        lidar_obj.group = group_name
        lidar_obj.srs = SpatialReference(
            srs)  # srs saved as user selection TXSP
        lidar_obj.bbox = get_bbox(las, srs)  # srs saved as 3857 for web maps
        lidar_obj.web_srs = lidar_obj.bbox.srid
        lidar_obj.centroid = lidar_obj.bbox.centroid  # srs saved as 3857 for web maps
        lidar_obj.point_count = get_point_count(las)
        lidar_obj.epsg = lidar_obj.srs.srid
        lidar_obj.file_size = float(las_file.size)
        x_scale, y_scale, z_scale = get_scale(las)
        lidar_obj.scale = (x_scale, y_scale, z_scale)
        offsets = get_offset(las)
        lidar_obj.offset = offsets
        mins_maxs = get_min_max(las)
        lidar_obj.min_max_XYZ = mins_maxs
        lidar_obj.version = get_version(las)
        lidar_obj.date_created = get_creation_date(las)
        lidar_obj.las_file = las_file
        lidar_obj.sys_id = get_system_identifier(las)
        lidar_obj.software_id = get_software_id(las)
        lidar_obj.save()
        las.close()
    return
예제 #3
0
def load_lidar_info(lidar_directory):
	print("Loading LIDARs data...")
	f = open(l_file, "w")

	for base, dirs, files in os.walk(lidar_directory):
		for lidar_file in files:
			lidar_file = lidar_directory + lidar_file
			f.write(lidar_file)

			os.system(laszip + " -i " + lidar_file + " -o " + lidar_file[:-3] + "LAS")

			inFile = File(lidar_file[:-3] + "LAS", mode='r')

			x_min = inFile.header.min[0]
			x_max = inFile.header.max[0]

			y_min = inFile.header.min[1]
			y_max = inFile.header.max[1]

			f.write(" " + str(x_min) + " " + str(y_min) + " " + str(x_max) + " " + str(y_max) + "\n")

			inFile.close()
			os.system("rm " + lidar_file[:-3] + "LAS")

	f.close()
	print("Load successful")
def store_point_cloud(filepath: str, points: np.ndarray, header):

    outFile = File(filepath, mode="w", header=header)
    outFile.x = points[:, 0] + header.min[0]
    outFile.y = points[:, 1] + header.min[1]
    outFile.z = points[:, 2] + header.min[2]
    outFile.close()
예제 #5
0
def importLidarDataToScene(context, filepath):

    # Get a reference to the scene
    scn = bpy.context.scene

    # Create a new mesh
    me = bpy.data.meshes.new("LiDARMesh")

    # Create a new object with the mesh
    obj = bpy.data.objects.new("LiDARObj", me)

    # Link the object to the scene
    scn.collection.objects.link(obj)

    # Read the file
    inFile = File(filepath, mode="r")

    # Get all the points
    point_records = inFile.points

    # X,Y,Z Coords Array
    coords = np.vstack((inFile.x, inFile.y, inFile.z)).transpose()

    # Update the Mesh
    me.from_pydata(coords, [], [])
    me.update()

    # Center to Origin
    obj.select_set(True)
    bpy.ops.object.origin_set(type='GEOMETRY_ORIGIN', center='MEDIAN')

    # Close the File
    inFile.close()

    return {'FINISHED'}
예제 #6
0
    def write_las_file(self):
        """ Create and write a new lidar file with the desirable points
        """
        if self.surfaces:
            self.out_full_path = os.path.join(
                self.out_dir,
                ('Surfaces_' + self.templates_dict['las'].format(self.name)))

        elif self.terrain:
            self.out_full_path = os.path.join(
                self.out_dir,
                ('Terrain_' + self.templates_dict['las'].format(self.name)))

        out_file = File(self.out_full_path,
                        mode='w',
                        header=self.in_file.header)
        if self.terrain:
            class_2_points, class_2_bool = self.get_points_by_class(
                self.class_flag)
            out_file.points = self.in_file.points[class_2_bool]

        elif self.surfaces:
            out_file.points = self.in_file.points[self.in_file.return_num == 1]

        out_file.close()
예제 #7
0
def writeFile(directory,name,header,coords):
    """Write a laz file using laspy and numpy arrays"""
    output = File(directory + name, mode = "w", header=header)
    output.x = coords[0]
    output.y = coords[1]
    output.z = coords[2]
    output.close()
예제 #8
0
 def __init__(self, points_file, class_file=''):
     # Load points file
     if points_file.endswith('.las') or points_file.endswith('.laz'):
         lfile = LasFile(points_file, mode='r')
         self.x = np.copy(lfile.X).astype('f8') * lfile.header.scale[0]
         self.y = np.copy(lfile.Y).astype('f8') * lfile.header.scale[1]
         self.z = np.copy(lfile.Z).astype('f8') * lfile.header.scale[2]
         self.i = np.copy(lfile.Intensity).astype('f8')
         self.r = np.copy(lfile.return_num).astype('f8')
         self.c = np.copy(lfile.Classification)
         lfile.close()
     elif points_file.endswith('.txt'):
         data = np.loadtxt(points_file, delimiter=',', dtype='f8')
         self.x = data[:, 0]
         self.y = data[:, 1]
         self.z = data[:, 2]
         self.i = data[:, 3]
         self.r = data[:, 4]
         if not class_file:
             if data.shape[1] > 5:
                 self.c = data[:, 5].astype('uint8')
             else:
                 self.c = np.zeros(self.x.shape, dtype='uint8')
         else:
             self.c = np.loadtxt(class_file, dtype='uint8')
     else:
         raise ValueError('Unknown file type extension: ' + points_file)
     self.filepath = points_file
     self.filename = os.path.splitext(os.path.basename(points_file))[0]
     if self.filename.endswith('_PC3'):
         self.filename = self.filename[:-4]
def readlas_convertgpd(file, epsg, luclass):
    """Reads a las file and converts it to a geopandas object"""

    # Read file
    pcloud = File(file, mode="r")

    # Convert to numpy
    pcloud_np = np.array(
        (pcloud.x, pcloud.y, pcloud.z, pcloud.red, pcloud.green, pcloud.blue,
         pcloud.raw_classification)).transpose()
    # Transform to pandas DataFrame
    pcloud_df = pd.DataFrame(pcloud_np)
    pcloud_df.columns = ['x', 'y', 'z', 'red', 'green', 'blue', 'ground']
    pcloud_df['ground'] = pcloud_df['ground'].apply(int).apply(str)
    pcloud_df['class'] = luclass

    # Transform to geopandas GeoDataFrame
    crs = None
    geometry = [Point(xyz) for xyz in zip(pcloud.x, pcloud.y, pcloud.z)]
    pcloud_geodf = gpd.GeoDataFrame(pcloud_df, crs=crs, geometry=geometry)
    epsg_str = 'epsg:' + epsg
    pcloud_geodf.crs = {'init': epsg_str}

    # Close file
    pcloud.close()

    return pcloud_geodf
예제 #10
0
 def save(self, output_file, class_file=''):
     if output_file.endswith('.txt'):
         if (not class_file and self.c.any()):
             np.savetxt(
                 output_file,
                 np.stack([self.x, self.y, self.z, self.i, self.r, self.c],
                          axis=1),
                 fmt='%.2f,%.2f,%.2f,%d,%d,%d')
         else:
             np.savetxt(output_file,
                        np.stack([self.x, self.y, self.z, self.i, self.r],
                                 axis=1),
                        fmt='%.2f,%.2f,%.2f,%d,%d')
         if class_file:
             self.save_classifications_txt(class_file)
     elif output_file.endswith('.las') or output_file.endswith('.laz'):
         lfile = LasFile(output_file,
                         mode='w',
                         header=LasHeader(x_scale=0.01,
                                          y_scale=0.01,
                                          z_scale=0.01))
         lfile.X = self.x / 0.01
         lfile.Y = self.y / 0.01
         lfile.Z = self.z / 0.01
         lfile.Intensity = self.i
         lfile.flag_byte = self.r
         lfile.Classification = self.c
         lfile.close()
     else:
         raise ValueError('Unknown file type extension: ' + output_file)
예제 #11
0
def do_hm(target_tile_path):
    # load tile for matching
    target_tile_name = target_tile_path.stem + target_tile_path.suffix
    try:
        target_tile = File(target_tile_path, mode='r') # this can take some time
     
        # use global to get the info, apologize to programming teachers
        global ref_tile
        global ky_lidar_fix_path
    
        # match histograms
        new_dist = hist_match(target_tile.intensity, ref_tile.intensity)
	
        # apply transformation
        new_tile_path = ky_lidar_fix_path / target_tile_name
        new_tile = File(new_tile_path, mode='w', header=target_tile.header)
        new_tile.points = target_tile.points
        new_tile.intensity = new_dist
        new_tile.close()
        return (True, new_tile_path)
    
    except:
        # if we can't load the file, that's a big problem, but it seems to happen
        # sometimes. 
        return (False, target_tile_path)
예제 #12
0
 def write(self):
     output = self.configs["paths"]["output"]
     points = np.array(self.points, dtype=self.dtype)
     #print self.header
     outfile = File(output + self.filename, mode="w", header=self.header)
     outfile.points = points
     outfile.close()
예제 #13
0
def save_las(xyzc, header, path):
    # header = Header()
    outfile = File(path, mode="w", header=header)
    outfile.X = xyzc[:, 0]
    outfile.Y = xyzc[:, 1]
    outfile.Z = xyzc[:, 2]
    outfile.Classification = xyzc[:, 3].astype(np.uint8)
    outfile.close()
예제 #14
0
def write_LAS(pc_xyz,
              v,
              output_las_fn,
              input_las_fn,
              cmap=cm.terrain,
              rescale='none'):
    import datetime
    from laspy.file import File
    from skimage import exposure
    import copy

    inFile = File(input_las_fn, mode='r')

    #normalize input and generate colors for height using colormap
    #stretch to 10-90th percentile
    #v_1090p = np.percentile(v, [10, 90])
    #stretch to 2-98th percentile
    v_0298p = np.percentile(v, [2, 98])
    if rescale == 'none':
        v_rescale = exposure.rescale_intensity(v,
                                               in_range=(v_0298p[0],
                                                         v_0298p[1]))
    elif rescale == 'median':
        bounds = np.round(np.median(np.abs(v_0298p)), decimals=2)
        v_rescale = exposure.rescale_intensity(v, in_range=(-bounds, bounds))

    colormap_terrain = cmap
    rgb = colormap_terrain(v_rescale)
    #remove last column - alpha value
    rgb = (rgb[:, :3] * (np.power(2, 16) - 1)).astype('uint16')
    outFile = File(output_las_fn, mode='w', header=inFile.header)
    new_header = copy.copy(outFile.header)
    #setting some variables
    new_header.created_year = datetime.datetime.now().year
    new_header.created_day = datetime.datetime.now().timetuple().tm_yday
    new_header.x_max = pc_xyz[:, 0].max()
    new_header.x_min = pc_xyz[:, 0].min()
    new_header.y_max = pc_xyz[:, 1].max()
    new_header.y_min = pc_xyz[:, 1].min()
    new_header.z_max = pc_xyz[:, 2].max()
    new_header.z_min = pc_xyz[:, 2].min()
    new_header.point_records_count = pc_xyz.shape[0]
    new_header.point_return_count = 0
    outFile.header.count = v.shape[0]
    new_header.scale = inFile.header.scale
    new_header.offset = inFile.header.offset
    outFile.X = (pc_xyz[:, 0] -
                 inFile.header.offset[0]) / inFile.header.scale[0]
    outFile.Y = (pc_xyz[:, 1] -
                 inFile.header.offset[1]) / inFile.header.scale[1]
    outFile.Z = (pc_xyz[:, 2] -
                 inFile.header.offset[2]) / inFile.header.scale[2]
    outFile.Red = rgb[:, 0]
    outFile.Green = rgb[:, 1]
    outFile.Blue = rgb[:, 2]
    outFile.close()
예제 #15
0
    def write_las_file(self):
        """ Create and write a new lidar file with the desirable points
        """

        self.dirs.set_output_dir()
        full_path = self.dirs.out_paths['las_terrain']
        self.dirs.create_dir(self.dirs.out_dirs['las'])

        out_file = File(full_path, mode='w', header=self.in_file.header)
        class_2_points, class_2_bool = self.get_points_by_class(
            self.class_flag)
        out_file.points = self.in_file.points[class_2_bool]
        out_file.close()
예제 #16
0
def make_las_file(data, file_name=''):
    my_header = header.Header()
    outFile = File(file_name, mode='w', header=my_header)

    # outFile.header.offset = np.amin(data, axis=0)[0:3]
    outFile.header.scale = [1, 1, 1]

    outFile.x = data[:, 0]
    outFile.y = data[:, 1]
    outFile.z = data[:, 2]
    outFile.raw_classification = data[:, 3]

    outFile.close()
예제 #17
0
파일: las_io.py 프로젝트: and-viceversa/ODM
def write_cloud(header,
                point_cloud,
                output_point_cloud_path,
                write_extra_dimensions=False):
    (h, scale, offset, evlrs, vlrs) = header

    # Open output file
    output_las_file = File(output_point_cloud_path,
                           mode='w',
                           header=h,
                           evlrs=evlrs,
                           vlrs=vlrs)

    if write_extra_dimensions:
        # Create new dimensions
        for name, dimension in point_cloud.extra_dimensions_metadata.items():
            output_las_file.define_new_dimension(
                name=name,
                data_type=dimension.get_las_type(),
                description="Dimension added by Ground Extend")

        # Assign dimension values
        for dimension_name, values in point_cloud.extra_dimensions.items():
            setattr(output_las_file, dimension_name, values)

    # Adapt points to scale and offset
    [x_scale, y_scale, z_scale] = scale
    [x_offset, y_offset, z_offset] = offset
    [x, y] = np.hsplit(point_cloud.xy, 2)
    output_las_file.X = (x.ravel() - x_offset) / x_scale
    output_las_file.Y = (y.ravel() - y_offset) / y_scale
    output_las_file.Z = (point_cloud.z - z_offset) / z_scale

    # Set color
    [red, green, blue] = np.hsplit(point_cloud.rgb, 3)
    output_las_file.red = red.ravel()
    output_las_file.green = green.ravel()
    output_las_file.blue = blue.ravel()

    # Set classification
    output_las_file.Classification = point_cloud.classification.astype(
        np.uint8)

    # Set header
    output_las_file.header.scale = scale
    output_las_file.header.offset = offset

    # Close files
    output_las_file.close()
예제 #18
0
def add_data(infile, configs):
	t_i = time.time()
	database = configs["paths"]["db"]
	conn = sqlite3.connect(database)
	#conn.execute("PRAGMA busy_timeout = 30000")
	c = conn.cursor()
	indata = File(infile, mode="r")
	filename = infile.split("/")[-1]
	points = indata.points
	return_num = indata.return_num
	num_returns = indata.num_returns
	scale = indata.header.scale
	data = []
	count = 0
	for i, elem in enumerate(points):
		X,Y,Z,intensity,flag_byte,raw_classification,scan_angle_rank,user_data,pt_src_id,gps_time=elem[0]
		#print data_text
		row = (
			filename,
			window(elem, 10, scale),
			window(elem, 5, scale),
			window(elem, 1, scale), 
			int(num_returns[i]),
			int(return_num[i]),
			int(X),
			int(Y),
			int(Z),
			int(intensity),
			int(flag_byte),
			int(raw_classification),
			int(scan_angle_rank),
			int(user_data),
			int(pt_src_id),
			float(gps_time)
		)
		data.append(row)
		#row = (window_index, elem)
		count +=1
	c.executemany('INSERT INTO pointcloud VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', data)
	conn.commit()
	indata.close()
	conn.close()
	t_f = time.time()
	print "Time for {} with {} records took {} minutes.".format(
		filename,
		count, 
		(t_f-t_i)/60.0
	)
예제 #19
0
 def get_first_returns_array(self):
 
     # Guardo el archivo para poder leerlo
     
     if self.partials_create:
         full_path = self.dirs.out_paths['las_surfaces']
         self.dirs.create_dir(self.dirs.out_dirs['las'])
     
     else:
         full_path = self.dirs.temp_full_paths['las_surfaces']
         self.dirs.create_dir(self.dirs.temp_dirs['temp_dir'])            
     
     out_file = File(full_path, mode='w', header=self.in_file.header)
     out_file.points = self.in_file.points[
             self.in_file.return_num == 1]
     out_file.close()
     
     #leo el archivo
     in_file = File(full_path, mode='r')
     scale = in_file.header.scale
     offset = in_file.header.offset
                     
     x = in_file.X
     y = in_file.Y
     z = in_file.Z
     
     x_dimension = x * scale[0] + offset[0]
     y_dimension = y * scale[1] + offset[1]
     z_dimension = z * scale[-1] + offset[-1]
     
     size = x_dimension.shape[0]
     
     x_array = x_dimension.reshape(size, 1)
     y_array = y_dimension.reshape(size, 1)
     z_array = z_dimension
     
     # Cerrar archivo para poder eliminarlo
     in_file.close()
     if not self.partials_create:
         self.dirs.remove_temp_file(full_path)
         self.dirs.remove_temp_dir(self.dirs.temp_dirs['temp_dir'])
         
     xy_array = np.concatenate((x_array, y_array), axis=1)
     self.surfaces_arrays_list = [xy_array, z_array]
예제 #20
0
def lidar_stats(request, lidar_id):
    """ Loads statistics page for selected file """
    # get file from db
    lidar_file = LidarFiles.objects.get(pk=lidar_id)

    # setup file access
    rstr_name = lidar_file.name.replace('.las', '_intensity.png')
    rstr_file = os.path.join(MEDIA_ROOT, 'rasters', rstr_name)
    tif_name = lidar_file.name.replace('.las', '_intensity.tif')
    tif_file = os.path.join(MEDIA_ROOT, 'rasters', tif_name)
    contour_name = lidar_file.name.replace('.las', '_contour_plot.png')
    contour_file = os.path.join(MEDIA_ROOT, 'rasters', contour_name)
    scatter_name = lidar_file.name.replace('.las', '_scatter_plot.png')
    scatter_file = os.path.join(MEDIA_ROOT, 'rasters', scatter_name)

    # create rasters if they do not already exist
    if not os.path.isfile(rstr_file):
        # open las file
        las = File(lidar_file.las_file.path, mode='r')

        # create raster and stats stuff
        create_rasters(las, tif_file, lidar_file.srs)
        make_z_contour_img(las, contour_file)
        make_z_scatter_plot(las, scatter_file)

        # create png
        save_as_png(tif_file)

        # close las file
        las.close()

    # save django raster_field
    # lidar_file.z_raster = z_raster
    # lidar_file.save()

    # render stats with images of rasters as <img/>
    context = {
        'lidar_file': lidar_file,
        'intensity': rstr_name,
        'scatter': scatter_name,
        'contour': contour_name,
    }
    return render(request, 'stats.html', context=context)
예제 #21
0
def data(fname):
    from laspy.file import File

    print('loading %s ..' % fname)
    f = File(fname, mode='r')
    x = f.x
    y = f.y
    z = f.z
    f.close()
    print('we have %.2e points' % len(x))

    print('add low noise ..')
    x += np.random.random(len(x)) / 1000.0
    y += np.random.random(len(x)) / 1000.0
    z += np.random.random(len(x)) / 1000.0

    print('remove points that are closer than 10cm ..')
    x, y, z = thinning(x, y, z, 0.1)
    print('we have %.2e points' % len(x))
    return (x, y, z)
예제 #22
0
    def write_las(self, file_name: str, alt_header: File = None):
        """ Writes the current points in a las format

        Header used will be the same as the one provided during loading otherwise given.
        """

        f = File(file_name,
                 mode='w',
                 header=alt_header if alt_header else self.header)
        data = self.data(transformed=False)

        f.X = data[:, 0]
        f.Y = data[:, 1]
        f.Z = data[:, 2]

        f.Red = data[:, 3]
        f.Green = data[:, 4]
        f.Blue = data[:, 5]

        f.close()
예제 #23
0
def readlas(fname):
    from laspy.file import File
    from subprocess import call

    r = call(['laszip', fname])
    if r:
        sys.exit('laszip ' + fname + ' failed')

    fn = '%s.las' % fname[:-4]
    f = File(fn)
    x = f.x
    y = f.y
    z = f.z
    l = f.classification
    f.close()
    r = call(['rm', fn])
    if r:
        sys.exit('rm ' + fn + ' failed')

    return np.transpose((x, y, z, l))
예제 #24
0
    def __init__(self, file, output_file, scale=1):

        inFile = File(file, mode="r")

        header_file = inFile.header

        self.x, self.y, self.z = inFile.x, inFile.y, inFile.z
        self.rn = inFile.return_num

        try:
            self.red, self.green, self.blue = inFile.red, inFile.green, inFile.blue
            print('LiDar file containing RGB channels')
        except:
            pass

        inFile.close()

        coords = np.vstack((self.z, self.y, self.x)).transpose()

        self.max_values = np.max(coords, axis=0).astype(int)
        self.min_values = np.min(coords, axis=0).astype(int)

        self.xr = np.array((1 / scale) * (coords[:, 2] - self.min_values[2]),
                           dtype=np.int)
        self.yr = np.array((1 / scale) * (self.max_values[1] - coords[:, 1]),
                           dtype=np.int)

        self.output_file = output_file
        self.scale = scale
        self.dimension = np.array(
            (1 / scale) * (self.max_values - self.min_values), dtype=np.int)
        self.n_points = len(self.xr)

        print('Metadata: ', header_file)
        print('Number of LiDar points: ', self.n_points)
        print('Maximum values in axis (z,y,x) are: ', self.max_values)
        print('Minimum values in axis (z,y,x) are: ', self.min_values)
        print('Cubic dimensions are: ', self.dimension)
def save_cloud(inFile, dir_out, filename, classif, conf):
    # Problème dans les données, certaines labels sont à 0
    label = inFile.classification
    ind = np.argwhere(label != 0)

    new_header = copy.copy(inFile.header)
    #Modification du point format id pour accéder au dimensions RGB
    new_header.data_format_id = 3
    #Create outfile
    outFile = dir_out + filename.replace('.laz', '_classify' + '.laz')
    outCloud = File(outFile,
                    mode="w",
                    header=new_header,
                    vlrs=inFile.header.vlrs)

    outCloud.define_new_dimension(name='classif',
                                  data_type=9,
                                  description="ntd")

    outCloud.define_new_dimension(name='conf', data_type=9, description="ntd")

    for dimension in inFile.point_format:
        if (dimension == inFile.point_format[13]):
            break
        dat = inFile.reader.get_dimension(dimension.name)[ind].reshape(-1)
        #        dat = dat[ind]
        outCloud.writer.set_dimension(dimension.name, dat)

    multiscale_features_raw = pd.DataFrame()
    features_raw = np.hstack([classif.reshape(-1, 1), conf.reshape(-1, 1)])
    features_raw = pd.DataFrame(features_raw)
    features_raw.columns = np.array(["classif", "conf"])
    multiscale_features_raw = pd.concat(
        [multiscale_features_raw, features_raw], axis=1)
    outCloud.classif = multiscale_features_raw.as_matrix(['classif']).ravel()
    outCloud.conf = multiscale_features_raw.as_matrix(['conf']).ravel()

    outCloud.close()
예제 #26
0
파일: las_io.py 프로젝트: and-viceversa/ODM
def read_cloud(point_cloud_path):
    # Open point cloud and read its properties
    las_file = File(point_cloud_path, mode='r')
    header = (las_file.header.copy(), las_file.header.scale,
              las_file.header.offset, las_file.header.evlrs,
              las_file.header.vlrs)
    [x_scale, y_scale, z_scale] = las_file.header.scale
    [x_offset, y_offset, z_offset] = las_file.header.offset

    # Calculate the real coordinates
    x = las_file.X * x_scale + x_offset
    y = las_file.Y * y_scale + y_offset
    z = las_file.Z * z_scale + z_offset

    cloud = PointCloud.with_dimensions(x, y, z, las_file.Classification,
                                       las_file.red, las_file.green,
                                       las_file.blue)

    # Close the file
    las_file.close()

    # Return the result
    return header, cloud
예제 #27
0
def z_adjustData(tile, source_data,target_data,filetype,outputfolder):

    tilename = tile.name

    source_tile = os.path.join(source_data, '{0}.{1}'.format(tilename,filetype)).replace('\\','/')
    target_tile = os.path.join(target_data, '{0}.{1}'.format(tilename,filetype)).replace('\\','/')
    temp_outputfile = os.path.join(outputfolder, '{0}.{1}'.format(tilename,'las')).replace('\\','/')
    outputfile = os.path.join(outputfolder, '{0}.{1}'.format(tilename,filetype)).replace('\\','/')
    
    #read the obfuscated tile
    sourcefile = File(source_tile, mode='r')
    targetfile = File(target_tile, mode='r')


    #get z values from source
    z_values=sourcefile.get_z_scaled()
    outfile = File(temp_outputfile, mode="w", header=targetfile.header)
    outfile.points=targetfile.points

    
    #Replace the z values from source file
    outfile.set_z_scaled(z_values)

    outfile.close()
    sourcefile.close()
    targetfile.close()


    #lascopy all x,y,z,classification based on the corrected gps time
    subprocessargs=['C:/LAStools/bin/las2las.exe', '-i', temp_outputfile, '-olaz', '-o', outputfile]
    subprocessargs=list(map(str,subprocessargs))    
    p = subprocess.run(subprocessargs,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=False, check=True, universal_newlines=True)

    if os.path.isfile(outputfile):
        #read the obfuscated tile
        log = f'Z replaced from {source_tile} -> {target_tile}'
        os.remove(temp_outputfile)
        print(log)

   
        return(True,outputfile,log)


    else:

        log = f'Failed replacing Z from {source_tile} -> {target_tile}'
        #os.remove(temp_outputfile)
        print(log)

        return(False,None,log)
min_x = np.min(in_pc_nparray[:, 0]) + shift
max_x = np.max(in_pc_nparray[:, 0]) + shift
step_x = resolution

min_y = np.min(in_pc_nparray[:, 1]) + shift
max_y = np.max(in_pc_nparray[:, 1]) + shift
step_y = resolution

bound_x = np.arange(min_x, max_x, step_x)
bound_y = np.arange(min_y, max_y, step_y)

target_x, target_y = np.meshgrid(bound_x, bound_y, indexing='ij')

# export as XYZ pcloud

x = np.ravel(target_x)
y = np.ravel(target_y)
z = np.ones(len(x))

false_intensity = np.zeros(len(x))

out_LAS = File(filename + "_target.las", mode="w", header=in_pc.header)
out_LAS.x = x
out_LAS.y = y
out_LAS.z = z
out_LAS.intensity = false_intensity
out_LAS.close()

end1 = time.time()
difftime1 = end1 - start1
print(("create target point: %f sec") % (difftime1))
예제 #29
0
def convertFile(tilename, inputfolder, outputfolder, filetype):

    inputfile = os.path.join(inputfolder,
                             '{0}.{1}'.format(tilename,
                                              filetype)).replace('\\', '/')
    temp_outputfile = os.path.join(outputfolder,
                                   '{0}.{1}'.format(tilename,
                                                    'las')).replace('\\', '/')
    outputfile = os.path.join(outputfolder,
                              '{0}.{1}'.format(tilename,
                                               filetype)).replace('\\', '/')

    try:
        inFile = File(inputfile, mode='r')

        header = inFile.header

        outfile = File(
            temp_outputfile,
            mode="w",
            header=header,
        )

        outfile.header.offset = [0.0, 0.0, 0.0]

        tic = time.perf_counter()
        X = inFile.get_x_scaled()
        Y = inFile.get_y_scaled()
        Z = inFile.get_z_scaled()
        E, N = transGDA94_to_ArgyleGrid(X, Y)

        outfile.points = inFile.points
        outfile.set_x_scaled(E)
        outfile.set_y_scaled(N)

        print(E, N, Z)

        toc = time.perf_counter()

        outfile.close()

        subprocessargs = [
            'C:/LAStools/bin/las2las.exe', '-i', temp_outputfile, '-olaz',
            '-o', outputfile
        ]
        subprocessargs = list(map(str, subprocessargs))
        p = subprocess.run(subprocessargs,
                           stdout=subprocess.PIPE,
                           stderr=subprocess.STDOUT,
                           shell=False,
                           check=True,
                           universal_newlines=True)

        log = f"{tilename} : Convertion completed in {toc - tic:0.4f}s"
        print(log)

        if os.path.isfile(outputfile):
            os.remove(temp_outputfile)

        return (True, outputfile, log)

    except:

        log = f"{tilename} : Convertion Failed"
        print(log)
        outfile.close()
        return (False, tilename, log)
    return (r, c[0], c[1], c[2])


if __name__ == '__main__':
    from laspy.file import File
    fname = \
        'data/mavicpro2_nadir_15deg_highq_dense_PC_10cm_aligned2_c2cdistances.las'

    print('reading', fname)
    f = File(fname)
    x = f.x
    y = f.y
    z = f.z
    classification = f.classification
    dz = getattr(f, 'c2c_absolute_distances_(z)').copy()
    f.close()

    print('c2c absolute distances (z):')
    print('pre min, mean, max:', dz.min(), dz.mean(), dz.max())
    j = (-2 <= dz) * (dz <= 2)
    xj, yj, dzj = x[j], y[j], dz[j]
    dzj *= 10
    print('post min, mean, max:', dzj.min(), dzj.mean(), dzj.max())

    print('extract ground class ..')
    pts = np.transpose((xj, yj, dzj))
    pts = pts[classification[j] == 2]

    print('fit spherical error model to ground component ..')
    ptsmin = pts.min(axis=0)
    R, x0, y0, z0 = fitsphere(pts - ptsmin)
    methodpointy = []
    methodpointz = []

    for point in methodpoints:
        methodpointx.append(point[0])
        methodpointy.append(point[1])
        methodpointz.append(point[2])

    print

    newoutput_file = File('method.las', mode="w", header=inFile.header)
    newoutput_file.X = methodpointx
    newoutput_file.Y = methodpointy
    newoutput_file.Z = methodpointz

    newoutput_file.close()
    inFile.close()

    #######################
    convertLasZip('out.las', 'out.laz')
    convertLasZip('method.las', 'method.laz')

    uploadToS3('out.laz', 'jippe-greyhound-to-las-test-dense',
               'potree_original.laz')
    uploadToS3('method.laz', 'jippe-greyhound-to-las-test-dense',
               'potree_method.laz')

    removeFile('out.las')
    removeFile('out.laz')
    removeFile('method.las')
    removeFile('method.laz')