TypeError:需要类似字节的对象,而不是'str',laspy

时间:2018-01-07 23:01:10

标签: python laspy

我是编程新手,希望使用将Las文件转换为网格文件。它一直给出错误

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

我知道fmt给出了一个字符串,所以我尝试fmt = '%1.2f'.encode()更改为二进制,但得到了同样的错误。

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')`

有人可以帮我解决一下。

2 个答案:

答案 0 :(得分:1)

f.write(bytes(header, 'UTF-8'))

答案 1 :(得分:0)

如果在使用'b'打开文件时使用python3,则无法将字符串写入文件,只能写入原始二进制数据。如果您有要写入文件的字符串,则应以文本模式打开(不使用'b')或将其转换为bytearray()

所以写入文件看起来像这样:

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