1.根据坐标读取遥感影像的单个像素值

# week 4: get pixel values at a set of coordinates by reading in one pixel at a time
import os, sys, time
from osgeo import gdal
from gdalconst import *# start timing
startTime = time.time()# coordinates to get pixel values for
xValues = [447520.0, 432524.0, 451503.0]
yValues = [4631976.0, 4608827.0, 4648114.0]# set directory
os.chdir('E:/data/GDAL/ospy_data4')
# register all of the drivers
gdal.AllRegister()# open the image
ds = gdal.Open('aster.img', GA_ReadOnly)
if ds is None:print('cannot open this file.')sys.exit(1)# get image size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount# get georeference info
transform = ds.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]# loop through the coordinates
for i in range(3):# get x,yx = xValues[i]y = yValues[i]# compute pixel offsetxOffset = int((x - xOrigin) / pixelWidth)yOffset = int((y - yOrigin) / pixelHeight)# create a string to print outs = str(x) + ' ' + str(y) + ' ' + str(xOffset) + ' ' + str(yOffset) + ' '# loop through the bandsfor j in range(bands):band = ds.GetRasterBand(j + 1)# read data and add the value to the stringdata = band.ReadAsArray(xOffset, yOffset, 1, 1)value = data[0, 0]s = s + str(value) + ' '# print out the data stringprint(s)
# figure out how long the script took to run
endTime = time.time()
print('The script took ' + str(endTime - startTime) + ' seconds.')

2.根据坐标读取遥感影像的单个像素值,通过获取图像所有像素值获得

# week 4:script to get pixel values at a set of coordinates by reading in entire bands
from osgeo import gdal
from gdalconst import *
import os, sys, time# start timing
startTime = time.time()# coordinates to get pixel values for
xValues = [447520.0, 432524.0, 451503.0]
yValues = [4631976.0, 4608827.0, 4648114.0]# set directory
os.chdir('E:/data/GDAL/ospy_data4')# register all of the drivers
gdal.AllRegister()# open the image
ds = gdal.Open('aster.img', GA_ReadOnly)
if ds is None:print('Cannot open aster.img')sys.exit(1)# get image size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount# get georeference info
transform = ds.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]# create a list to store band data in
bandList = []# read in bands and store all the data in bandList
for i in range(bands):band = ds.GetRasterBand(i + 1)data = band.ReadAsArray(0, 0, cols, rows)bandList.append(data)# loop through the coordinates
for i in range(3):x = xValues[i]y = yValues[i]# compute pixel offsetxOffset = int((x - xOrigin) / pixelWidth)yOffset = int((y - yOrigin) / pixelHeight)# create a string to print outs = str(x) + ' ' + str(y) + ' ' + str(xOffset) + ' ' + str(yOffset) + ' '# loop through the bands and get the pixel valuefor j in range(bands):data = bandList[j]value = data[xOffset-1, yOffset-1]s = s + str(value)+' '# print out the data stringprint(s)# figure out how long the script took to run
endTime = time.time()
print('The script took ' + str(endTime - startTime) + ' seconds.')

3.Assignment 4a:Read pixel values from an image

  • Print out the pixel values for all three bands of aster.img at the points contained in sites.shp •
  • Use any method of reading the raster data that you want, but I would suggest one pixel at a time (fastest in this case since we don't need much data)

1)自己写的代码,现获取所有sities的坐标后再获取全部的pixel values

# Assignment 4a: Read pixel values from an image
# write by myself
from osgeo import gdal
from gdalconst import *
import ogr, os, sys# set the directory
os.chdir('E:/data/GDAL/ospy_data4')# set the driver
driver = ogr.GetDriverByName('ESRI Shapefile')
# open the file
siteDS = driver.Open('sites.shp', 0)
if siteDS is None:print('Cannot open sites.shp')sys.exit(1)# get the layer
siteLy = siteDS.GetLayer()
# get the feature
siteFe = siteLy.GetNextFeature()# create lists to store the x,y coordination of the feature
sitePosX = []
sitePosY = []# cycle the feature to get the x,y coordination
while siteFe:geom = siteFe.GetGeometryRef()fex = geom.GetX()fey = geom.GetY()sitePosX.append(fex)sitePosY.append(fey)siteFe.Destroy()siteFe = siteLy.GetNextFeature()# create a txt file to store result
txt = open('output.txt', 'w')# register all of the drivers
gdal.AllRegister()
# open the image
asterDS = gdal.Open('aster.img', GA_ReadOnly)
if asterDS is None:print('Cannot open aster.img')sys.exit(1)# get the image size
rows = asterDS.RasterYSize
cols = asterDS.RasterXSize
bands = asterDS.RasterCount# get the georeference info
transform = asterDS.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]# get the pixel value of the coordination
for i in range(len(sitePosX)):x = sitePosX[i]y = sitePosY[i]# get the offsetxOffset = int((x - xOrigin) / pixelWidth)yOffset = int((y - yOrigin) / pixelHeight)s = str(i + 1) + ' ' + str(x) + ' ' + str(y) + ' ' + str(xOffset) + ' ' + str(yOffset) + ' '# get all bands of the pixel valuefor j in range(bands):band = asterDS.GetRasterBand(j + 1)data = band.ReadAsArray(xOffset, yOffset, 1, 1)value = data[0, 0]s = s + str(value) + ' 's = s + '\n'# write to a text filetxt.write(s)print(s)# destroy datasource
siteDS.Destroy()

2)参考答案给的代码,每获取一个site坐标就获取该坐标的pixel value

import os, sys
try:from osgeo import ogr, gdalfrom osgeo.gdalconst import *os.chdir('E:/data/GDAL/ospy_data4')
except ImportError:import ogr, gdalfrom gdalconst import *os.chdir('E:/data/GDAL/ospy_data4')# open the shapefile and get the layer
driver = ogr.GetDriverByName('ESRI Shapefile')
shp = driver.Open('sites.shp')
if shp is None:print('Could not open sites.shp')sys.exit(1)
shpLayer = shp.GetLayer()# register all of the GDAL drivers
gdal.AllRegister()# open the image
img = gdal.Open('aster.img', GA_ReadOnly)
if img is None:print('Could not open aster.img')sys.exit(1)# get image size
rows = img.RasterYSize
cols = img.RasterXSize
bands = img.RasterCount# get georeference info
transform = img.GetGeoTransform()
xOrigin = transform[0]
yOrigin = transform[3]
pixelWidth = transform[1]
pixelHeight = transform[5]# loop through the features in the shapefile
feat = shpLayer.GetNextFeature()
while feat:geom = feat.GetGeometryRef()x = geom.GetX()y = geom.GetY()# compute pixel offsetxOffset = int((x - xOrigin) / pixelWidth)yOffset = int((y - yOrigin) / pixelHeight)# create a string to print outs = feat.GetFieldAsString('ID') + ' '# loop through the bandsfor j in range(bands):band = img.GetRasterBand(j + 1)  # 1-based index# read data and add the value to the stringdata = band.ReadAsArray(xOffset, yOffset, 1, 1)value = data[0, 0]s = s + str(value) + ' '# print out the data stringprint(s)# get the next featurefeat.Destroy()feat = shpLayer.GetNextFeature()# close the shapefile
shp.Destroy()

4.为了更有效率地读取栅格,一种更好的方法是分块读取数据。数据文件中给出了一个utils.py文件中的GetBlockSize()函数可以实现获取图像中的xBlockSize和yBlockSize,但是在我的电脑里不能运行。于是尝试手动定义xBlockSize和yBlockSize,更改了几次数值发现程序运行结果都是一样的,因此我认为手动赋值给xBlockSize和yBlockSize也是可行的。下面代码是循环分块读取栅格数据的样例,具体原理可参见PPT

from osgeo import gdal
from gdalconst import *
import numpy as np
import os
import sys
import utilsos.chdir('E:/data/GDAL/ospy_data4')
gdal.AllRegister()ds = gdal.Open('aster.img', GA_ReadOnly)
if ds is None:print('Cannot open aster.img')sys.exit(1)rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCountband = ds.GetRasterBand(1)
# 由于utils.py文件中找不到_gdal模块,因此以下三行代码不能使用
# xblocksize和yblocksize改为手动设置
# 更改了几个值发现程序运行最终结果不变
# blockSizes = utils.GetBlockSize(band)
# xBlockSize = blockSizes[0]
# yBlockSize = blockSizes[1]xBlockSize = 20
yBlockSize = 20count = 0for i in range(0, rows, yBlockSize):if (i + yBlockSize) < rows:numRows = yBlockSizeelse:numRows = rows - ifor j in range(0, cols, xBlockSize):if (j + xBlockSize) < cols:numCols = xBlockSizeelse:numCols = cols - jdata = band.ReadAsArray(j, i, numCols, numRows).astype(np.float)mask = np.greater(data, 0)count = count + np.sum(np.sum(mask))print('Number of non-zero pixels: ', count)

5. Assignment 4b:

  • Write a script to calculate the average pixel value for the first band in aster.img
  • Read in the data one block at a time
  • Do the calculation two ways :
    • Including zeros in the calculation
    • Ignoring zeros in the calculation

1)自己写的代码

# Assignment 4b:Write a script to calculate the average pixel value for the first band in aster.img
# write by myself
# import models
from osgeo import gdal
from gdalconst import *
import numpy as np
import os
import sys# set the directory
os.chdir('E:/data/GDAL/ospy_data4')# register all drivers
gdal.AllRegister()# open the file
ds = gdal.Open('aster.img', GA_ReadOnly)
if ds is None:print('Cannot open aster.img')sys.exit(1)# get the raster size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount# get the first band and set blocksize
band = ds.GetRasterBand(1)
xBlockSize = 10
yBlockSize = 10sumIncludeZero = 0.0
zeroCount = 0# cycle row blocksize
for i in range(0, rows, yBlockSize):# set yblocksizeif (i + yBlockSize) < rows:ySize = yBlockSizeelse:ySize = rows - i# cycle col blocksizefor j in range(0, cols, xBlockSize):# set xblocksizeif (j + xBlockSize) < cols:xSize = xBlockSizeelse:xSize = cols - j# read block datadata = band.ReadAsArray(j, i, xSize, ySize).astype(np.float)sumIncludeZero = sumIncludeZero + np.sum(np.sum(data))mask = np.greater(data, 0)zeroCount = zeroCount + np.sum(np.sum(mask))# calculate
avg_includeZero = sumIncludeZero / (rows * cols)
avg_ignoreZero = sumIncludeZero / zeroCount
print('Average include zero: ', avg_includeZero)
print('Average ignore zero: ', avg_ignoreZero)

2)参考答案给的代码

# Assignment 4b:Write a script to calculate the average pixel value for the first band in aster.img
#reference answer
import os, sys
# import utilsuse_numeric = Truetry:from osgeo import ogr, gdalfrom osgeo.gdalconst import *import numpyos.chdir('E:/data/GDAL/ospy_data4')use_numeric = False
except ImportError:import ogr, gdalfrom gdalconst import *import Numericos.chdir('E:/data/GDAL/ospy_data4')# register all of the GDAL drivers
gdal.AllRegister()# open the image
ds = gdal.Open('aster.img', GA_ReadOnly)
if ds is None:print('Could not open aster.img')sys.exit(1)# get image size
rows = ds.RasterYSize
cols = ds.RasterXSize
bands = ds.RasterCount# # get the band and block sizes
# band = ds.GetRasterBand(1)
# blockSizes = utils.GetBlockSize(band)
# xBlockSize = blockSizes[0]
# yBlockSize = blockSizes[1]
band = ds.GetRasterBand(1)
xBlockSize = 20
yBlockSize = 20# initialize variables
count = 0
total = 0# loop through the rows
for i in range(0, rows, yBlockSize):if i + yBlockSize < rows:numRows = yBlockSizeelse:numRows = rows - i# loop through the columnsfor j in range(0, cols, xBlockSize):if j + xBlockSize < cols:numCols = xBlockSizeelse:numCols = cols - j# read the data and do the calculationsif use_numeric:data = band.ReadAsArray(j, i, numCols, numRows).astype(Numeric.Float)mask = Numeric.greater(data, 0)count = count + Numeric.sum(Numeric.sum(mask))total = total + Numeric.sum(Numeric.sum(data))else:data = band.ReadAsArray(j, i, numCols, numRows).astype(numpy.float)mask = numpy.greater(data, 0)count = count + numpy.sum(numpy.sum(mask))total = total + numpy.sum(numpy.sum(data))# print results
print('Ignoring 0:', total / count)
print('Including 0:', total / (rows * cols))

数据下载:https://download.csdn.net/download/qq_37935516/10795361

【GDAL学习】用GDAL读取栅格数据相关推荐

  1. GDAL / OGR 学习手册 [02] :栅格数据读取

    目录 一.栅格数据驱动 二.gdal.Open 三.gdal.Dataset 四.获取影像的基本信息 1. 获取影像元数据 2. 获取影像基本信息 一.栅格数据驱动 GDAL 通过数据驱动来识别各种类 ...

  2. C# GDAL 学习一

    最近一直琢磨如何用C#+GDAL读取栅格数据(.tif或.img),运气不错的在GDAL 的官网上找到一部分源码.经过本人测试,效果还不错.学习还将继续深入下去. 参考网址:http://trac.o ...

  3. GDAL学习笔记02:GDAL基础知识

    你的习惯决定了你会成为什么样的人. GDAL学习笔记02:GDAL基础知识 前言 1. 版本 2. 摘要 3. 说明 4. 微信公众号GISRSGeography 一.GDAL简介 二.导入GDAL ...

  4. Python GDAL学习笔记(一)

    目录 一.读取tif格式影像 导入GDAL模块并查看版本/位置 打开影像 查看行列号和波段数 查看影像文件描述和其他属性 打开数据集波段并获取统计信息 利用numpy将波段数据写入数组 将波段数据写入 ...

  5. gdal 压缩tif_Python | GDAL处理影像

    GDAL栅格数据处理 栅格数据介绍 栅格数据读取 读取部分数据集 坐标变换 重采样 什么是栅格数据 基本上是一个大的二维或三维数组 没有独立的几何对象,只有像素的集合 二维:黑白图片 三维:彩色/假彩 ...

  6. R语言入门——读取栅格数据参数解读

    读取栅格数据 引言 1.数据读入 2.参数解读 2.1 class (类) 2.2 dimensions(维度) 2.3 resolution (像素) 2.4 extent(范围) 2.5 name ...

  7. TF学习——TF数据读取:TensorFlow中数据读这三张图片的5个epoch +把读取的结果重新存到read 文件夹中

    TF学习--TF数据读取:TensorFlow中数据读这三张图片的5个epoch +把读取的结果重新存到read 文件夹中 目录 实验展示 代码实现 实验展示 代码实现 1.如果设置shuffle为T ...

  8. ffplay.c学习-2-数据读取线程

    ffplay.c学习-2-数据读取线程 目录 准备⼯作 avformat_alloc_context 创建上下⽂ ic->interrupt_callback avformat_open_inp ...

  9. Adam学习25之读取sam生成的alignmentRecord含recordGroupDictionary

    Adam学习25之读取sam生成的alignmentRecord含recordGroupDictionary 1.代码: package org.bdgenomics.adam.testimport ...

最新文章

  1. 【Flutter】Hero 动画 ( Hero 动画使用流程 | 创建 Hero 动画核心组件 | 创建源页面 | 创建目的页面 | 页面跳转 )
  2. C#面向对象--继承
  3. leetcode 449. Serialize and Deserialize BST | 449. 序列化和反序列化二叉搜索树(BST后序遍历性质)
  4. Ubuntu KDE中 Kaccounts-provider 问题
  5. 互联网日报 | 爱奇艺会员宣布11月13日起涨价;淘宝特价版月活用户破7000万;我国成功发射一箭十三星...
  6. Java项目经验是程序员成长的重要经验
  7. Cortex-M3学习笔记(一)
  8. 读取 Excel 之 Epplus
  9. Spyder远程连接矩池云
  10. Android 网络管理
  11. CCNP交换实验(5) -- 网关热备冗余
  12. HTB TIER 2 Archetype wp
  13. OTU/ASV/Feature tabel 表格 过滤 相对丰度 微生物
  14. 怎么快速学会计算机程序知识,零基础学电脑怎样才能学得快,自学电脑的基础知识分享...
  15. python当前时间加一分钟_Python实现的当前时间多加一天、一小时、一分钟操作示例...
  16. 电脑装机兼容性测试软件,四款产品内部兼容性测试
  17. goahead 2.5 碰到的问题
  18. T560和为k的子数组
  19. 降低 Spark 计算成本 50.18 %,使用 Kyligence 湖仓引擎构建云原生大数据底座,为计算提速 2x
  20. E19系列与E10系列lora扩频技术无线模块选型指南

热门文章

  1. 二维码中文乱码问题解决
  2. ----顾问应该是探索新领域的向导,而不是拉雪橇的狗
  3. Android应用数据清理命令(adb clear)的使用执行报错问题解决
  4. 洛谷 P2735 [USACO3.4]网 Electric Fences
  5. Objective-C中对IPhone设备震动的调用
  6. c语言tab什么意思_C语言入门 — 一篇最全的C语言基础知识。
  7. NLP以赛代练 Task 1:赛题理解
  8. Intel Realsense D435i相关资料
  9. 微信授权登录问题【公众号登录、PC扫描登录】
  10. opencv-python实现PS中的油漆填充功能,一键填充颜色 以及opencv经常报错的可能原因