用python将函数输出到csv

2024-06-16 09:06:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的初学者,需要以csv/xlsx格式导出函数输出。 请看我的代码。 我需要把pixel2coord函数的输出打印到csv。谢谢

from osgeo import gdal
# Open raster file
ds = gdal.Open('C:\\Users\\ADMIN\\Desktop\\datanew\\ndvi_alig_landsat_clipped.img')
# GDAL affine transform parameters, According to gdal documentation xoff/yoff are image left corner, a/e are pixel wight/height and b/d is rotation and is zero if image is north up. 
xoff, a, b, yoff, d, e = ds.GetGeoTransform() 
def pixel2coord(x, y):
    """Returns global coordinates from pixel x, y coords"""   
    xp = a * x + b * y + xoff
    yp = d * x + e * y + yoff
    return(xp, yp)
# get columns and rows of your image from gdalinfo
rows = 15381+1
colms = 15081+1

if __name__ == "__main__":
    for row in  range(0,rows):
        for col in  range(0,colms): 
            print pixel2coord(col,row)

Tags: andcsv函数fromimageisdsopen
1条回答
网友
1楼 · 发布于 2024-06-16 09:06:46

以下是您感兴趣的代码:

if __name__ == "__main__":
    file=open("file.csv","w") ## open file in write mode
    for row in  range(0,rows):
        for col in  range(0,colms): 
            x,y = pixel2coord(col,row)
            print "({},{})".format(x,y)
            lat= ## x or y
            long= ## x or y
            file.write("{};{}\n".format(lat,long)) ## write each coordinate comma-separated

注:我使用的是欧洲风格的csv(分号分隔),如果你是美国人,可以用逗号代替分号(字符串内)

相关问题 更多 >