x = self.x_origin + (j + 0.5) * self.pixel_width y = self.y_origin + (i + 0.5) * self.pixel_height z = val self.iteSize += 1 return x, y, z dsm_path = 'C:\sanwei\jianmo\Productions\Production_2\Production_2_DSM_part_2_2.tif' dsm_data = gdal.Open(dsm_path) dsm_array = dsm_data.ReadAsArray() spiral_iterator = SpiralIterator(dsm_array,x=810,y=500) while spiral_iterator.hasNext(): x, y, z = spiral_iterator.get() print(f'Value at ({x},{y}):{z}')这段代码怎么改可以将打印的坐标保存为文档
时间: 2023-12-15 16:04:41 浏览: 91
你可以将打印出来的坐标以及对应的值写入到一个文本文件中,方法和上面类似。以下是修改后的代码示例:
```python
import gdal
class SpiralIterator:
def __init__(self, array, x=0, y=0):
self.array = array
self.x_origin = x
self.y_origin = y
self.pixel_width = 1
self.pixel_height = 1
self.iteSize = 0
self.i = 0
self.j = 0
self.di = 0
self.dj = 1
self.width = array.shape[1]
self.height = array.shape[0]
def hasNext(self):
return self.iteSize < self.width * self.height
def get(self):
val = self.array[self.i, self.j]
x = self.x_origin + (self.j + 0.5) * self.pixel_width
y = self.y_origin + (self.i + 0.5) * self.pixel_height
self.iteSize += 1
self.i, self.j, self.di, self.dj = self.getNextIndex()
return x, y, val
def getNextIndex(self):
if (self.i + self.di < 0 or self.i + self.di == self.height
or self.j + self.dj < 0 or self.j + self.dj == self.width
or self.array[self.i + self.di, self.j + self.dj] is None):
self.di, self.dj = self.dj, -self.di
return self.i + self.di, self.j + self.dj, self.di, self.dj
dsm_path = r'C:\sanwei\jianmo\Productions\Production_2\Production_2_DSM_part_2_2.tif'
dsm_data = gdal.Open(dsm_path)
dsm_array = dsm_data.ReadAsArray()
spiral_iterator = SpiralIterator(dsm_array, x=810, y=500)
# 打开文件
with open('coordinates.txt', 'w') as f:
while spiral_iterator.hasNext():
x, y, z = spiral_iterator.get()
print(f'Value at ({x},{y}): {z}')
# 将坐标和对应的值写入文件
f.write(f'({x},{y}): {z}\n')
print('Done!')
```
在这个例子中,我们使用了Python的with语句来打开文件,它可以自动管理文件的打开和关闭,避免了手动关闭文件时可能出现的错误。在while循环中,我们将打印的坐标和对应的值写入到了文件中。文件的名字可以根据你的需要自行修改。运行结束后,你可以在相应的目录下找到保存好的coordinates.txt文件。
阅读全文