TypeError: a bytes-like object is required, not 'str', laspy

761 Views Asked by At

I am new to programming and wanted to convert Las file into grid file using . It keeps giving error

"TypeError: a bytes-like object is required, not 'str'". 

I know fmt gives a string, so I tried fmt = '%1.2f'.encode() to change in to binary, but got the same error.

from laspy.file import File
import numpy as np

source = "/655-7878.las"

target = "/lidar.asc"
cell = 1.0

NODATA = 0

las = File(source, mode = "r")

#xyz min and max
min = las.header.min
max = las.header.max
#Get the x axis distance
xdist = max[0] - min[0]

#Get the y axis distance
ydist = max[1] - min[1]

#Number of columns for our grid
cols = int((xdist)/cell)
#Number of rows for our grid
rows = int((ydist)/cell)


cols += 1
rows += 1

#Track how many elevation
#values we aggregate
count = np.zeros((rows, cols)).astype(np.float32)
#Aggregate elevation values
zsum = np.zeros((rows, cols)).astype(np.float32)

#Y resolution is negative
ycell = -1 * cell
#Project x,y values to grid
projx =(las.x -min[0]) / cell
projy = (las.y - min[1])/ ycell
#Cas to integers and clip for use as index
ix = projx.astype(np.int32)
iy = projy.astype(np.int32)

 #Loop through x,y,z arrays, add to grid shape and aggregate values for averaging
for x,y,z in np.nditer([ix, iy, las.z]):
    count[y, x] +=1
    zsum[y, x]+=z
# Change 0 values to 1 to avoid numpy warnings and NaN values in array
nonzero = np.where(count>0, count, 1)
#Average our z values
zavg = zsum/nonzero
 #Interpolate 0 values in array to avoid any holes in the grid
mean = np.ones((rows, cols)) * np.mean(zavg)
left = np.roll(zavg, -1,1)
lavg = np.where(left>0, left, mean)
right = np.roll(zavg, 1, 1)
ravg = np.where(right>0, right, mean)
interpolate = (lavg + ravg)/2
fill = np.where(zavg>0, zavg, interpolate)

#Create ASCII DEM header
header = "ncols          %s\n" % fill.shape[1]
header += "nrows         %s\n" % fill.shape[0]
header += "xllcorner     %s\n"  % min[0]
header += "yllcorner     %s\n"  % min[1]
header += "cellsize      %s\n"  % cell
header += "NODATA_value        %s\n" % NODATA

#Open the output file, add the header, save the array
with open(target, "wb") as f:
    f.write(header)
# The fmt string ensures we output floats
#That have at least one number  but only two decimal places
    np.savetxt(f, fill, fmt = '%1.2f')`

Can someone please help me to sort it out.

2

There are 2 best solutions below

2
On

if you are using python3 when you open a file with 'b' you can't write strings to the file, only raw binary data . if you have a string you want to write to the file you should either open it in text mode (without 'b') or convert it to a bytearray()

so writing to file would look like this:

with open(target, "wb") as f:
    f.write(bytearray(header,'utf-8'))
0
On
f.write(bytes(header, 'UTF-8'))