首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >TypeError:需要类似字节的对象,而不是“str”、laspy

TypeError:需要类似字节的对象,而不是“str”、laspy
EN

Stack Overflow用户
提问于 2018-01-08 07:01:10
回答 2查看 634关注 0票数 2

我是编程新手,想使用laspy将Las文件转换为网格文件。它不断地给出错误

代码语言:javascript
复制
"TypeError: a bytes-like object is required, not 'str'". 

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

代码语言:javascript
复制
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')`

有没有人能帮我理清头绪。

EN

回答 2

Stack Overflow用户

发布于 2020-06-17 19:34:48

代码语言:javascript
复制
f.write(bytes(header, 'UTF-8'))
票数 1
EN

Stack Overflow用户

发布于 2018-01-09 17:44:15

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

因此,写入文件将如下所示:

代码语言:javascript
复制
with open(target, "wb") as f:
    f.write(bytearray(header,'utf-8'))
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48142357

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档