Geoprocessing with Python (一)

Week 7: Misc stuff

Convert a shapefile to KML

  • Use “STATE_NAME” as the name field for the KML features
  • Include all of the attributes in the description
第七周:杂项

shapefile 转换 KML

  • 使用“STATE_NAME”作为 KML要素的Name字段
  • 在描述中包含所有的属性
ogr2ogr -f "KML" -dsco NameField="STATE_NAME" states.kml states.shp
Week 6 : More raster processing

Use a 3x3 high-pass filter to detect edges in band 1 of smallaster.img.

  • Use pixel notation (this is why you’re using smallaster.img – it would take forever to run on aster.img).
  • The output type will be float.
  • Don’t build pyramids so you can easily compare your output with output.img.

Use a 3x3 high-pass filter to detect edges in band 1 of aster.img.

  • Use slice notation. It will take a minute or two to run, so you should probably test on smallaster.img and then run in on aster.img after everything seems to be working.
  • The output type will be float.
  • Don’t build pyramids so you can easily compare your output with output.img.
更多栅格影像处理

使用 3x3 高通滤波来检测 smallaster.img (波段1) 边缘。

  • 采用像素表示法。
  • 输出类型 float。
  • 不建立金子塔影像

使用 3x3 高通滤波来检测 aster.img (波段1) 边缘。

  • 采用切片表示法。
  • 输出类型 float。
  • 不建立金子塔影像
# homework 6a
# high-pass filter using pixel notation
import os, sys, time
import numpy as np

from osgeo import gdal
from osgeo.gdalconst import *

import matplotlib.pyplot as plt
#plt.rcParams['figure.dpi'] = 300 #分辨率

start = time.time()

#os.chdir('c:/temp/py6')
# register all of the GDAL drivers
gdal.AllRegister()

# open the image
inDs = gdal.Open('smallaster.img', GA_ReadOnly)
if inDs is None:
  print ('Could not open smallaster.img')
  sys.exit(1)

# get image size
rows = inDs.RasterYSize
cols = inDs.RasterXSize

# read the input data
inBand = inDs.GetRasterBand(1)
inData = inBand.ReadAsArray(0, 0, cols, rows).astype(np.float32)

# do the calculation
outData = np.zeros((rows, cols), np.float32)

for i in range(1, rows-1):
    for j in range(1, cols-1):
        outData[i,j] = ((-0.7 * inData[i-1,j-1]) + 
                        (-1.0 * inData[i-1,j])   + 
                        (-0.7 * inData[i-1,j+1]) + 
                        (-1.0 * inData[i,j-1])   + 
                        ( 6.8 * inData[i,j])     + 
                        (-1.0 * inData[i,j+1])   +
                        (-0.7 * inData[i+1,j-1]) + 
                        (-1.0 * inData[i+1,j])   + 
                        (-0.7 * inData[i+1,j+1]))
# create the output image
driver = inDs.GetDriver()
outDs = driver.Create('highpass1.img', cols, rows, 1, GDT_Float32)
if outDs is None:
  print ('Could not create highpass1.img')
  sys.exit(1)
outBand = outDs.GetRasterBand(1)

# write the output data
outBand.WriteArray(outData, 0, 0)

# flush data to disk, set the NoData value and calculate stats
outBand.FlushCache()
stats = outBand.GetStatistics(0, 1)

# georeference the image and set the projection
outDs.SetGeoTransform(inDs.GetGeoTransform())
outDs.SetProjection(inDs.GetProjection())

print (time.time() - start, 'seconds')

plt.subplot(121)
plt.imshow(inData,cmap='gray')
plt.subplot(122)
plt.imshow(outData,cmap='gray')
plt.savefig("res1.png")
inDs = None
outDs = None
74.08075737953186 seconds

在这里插入图片描述

# homework 6b
# high-pass filter using slice notation
import os, sys, time
import numpy as np

from osgeo import gdal
from osgeo.gdalconst import *

import matplotlib.pyplot as plt

#plt.rcParams['figure.dpi'] = 300 #分辨率

start = time.time()

#os.chdir('c:/temp/py6')

# register all of the GDAL drivers
gdal.AllRegister()

# open the image
inDs = gdal.Open('smallaster.img', GA_ReadOnly)
if inDs is None:
  print ('Could not open aster.img')
  sys.exit(1)

# get image size
rows = inDs.RasterYSize
cols = inDs.RasterXSize

# read the input data
inBand = inDs.GetRasterBand(1)
inData = inBand.ReadAsArray(0, 0, cols, rows).astype(np.uint32)


# do the calculation
outData = np.zeros((rows, cols), np.float32)

outData[1:rows-1,1:cols-1] = ((-0.7 * inData[0:rows-2,0:cols-2]) +
                              (-1.0 * inData[0:rows-2,1:cols-1]) +
                              (-0.7 * inData[0:rows-2,2:cols]) +
                              (-1.0 * inData[1:rows-1,0:cols-2]) + 
                              ( 6.8 * inData[1:rows-1,1:cols-1]) +
                              (-1.0 * inData[1:rows-1,2:cols]) + 
                              (-0.7 * inData[2:rows,0:cols-2]) +
                              (-1.0 * inData[2:rows,1:cols-1]) + 
                              (-0.7 * inData[2:rows,2:cols]))

# outData[1:rows-1,1:cols-1] = ((-1.0 * inData[0:rows-2,0:cols-2]) +
#                               (-1.0 * inData[0:rows-2,1:cols-1]) +
#                               (-1.0 * inData[0:rows-2,2:cols]) +
#                               (-1.0 * inData[1:rows-1,0:cols-2]) + 
#                               ( 8.0 * inData[1:rows-1,1:cols-1]) +
#                               (-1.0 * inData[1:rows-1,2:cols]) + 
#                               (-1.0 * inData[2:rows,0:cols-2]) +
#                               (-1.0 * inData[2:rows,1:cols-1]) + 
#                               (-1.0 * inData[2:rows,2:cols]))


# create the output image
driver = inDs.GetDriver()
outDs = driver.Create('highpass3.img', cols, rows, 1, GDT_Float32)#GDT_CInt32
if outDs is None:
  print ('Could not create highpass3.img')
  sys.exit(1)
outBand = outDs.GetRasterBand(1)

# write the output data
outBand.WriteArray(outData, 0, 0)

# flush data to disk, set the NoData value and calculate stats
outBand.FlushCache()
stats = outBand.GetStatistics(0, 1)

# georeference the image and set the projection
outDs.SetGeoTransform(inDs.GetGeoTransform())
outDs.SetProjection(inDs.GetProjection())

print (time.time() - start, 'seconds')

plt.subplot(121)
plt.imshow(inData,cmap='gray')

plt.subplot(122)
plt.imshow(outData,cmap='gray')
plt.savefig("res2.png")
inDs = None
outDs = None


0.48896169662475586 seconds

在这里插入图片描述

# homework 6b
# low-pass filter using slice notation
import os, sys, time
import numpy as np

from osgeo import gdal
from osgeo.gdalconst import *

import matplotlib.pyplot as plt

#plt.rcParams['figure.dpi'] = 300 #分辨率

start = time.time()

#os.chdir('c:/temp/py6')

# register all of the GDAL drivers
gdal.AllRegister()

# open the image
inDs = gdal.Open('smallaster.img', GA_ReadOnly)
if inDs is None:
  print ('Could not open aster.img')
  sys.exit(1)

# get image size
rows = inDs.RasterYSize
cols = inDs.RasterXSize

# read the input data
inBand = inDs.GetRasterBand(1)
inData = inBand.ReadAsArray(0, 0, cols, rows).astype(np.uint32)

#plt.figure(figsize=(10,10)) 


# do the calculation
outData = np.zeros((rows, cols), np.float32)

outData[1:rows-1,1:cols-1] = ((0.111 * inData[0:rows-2,0:cols-2]) +
                              (0.111 * inData[0:rows-2,1:cols-1]) +
                              (0.111* inData[0:rows-2,2:cols]) +
                              (0.111 * inData[1:rows-1,0:cols-2]) + 
                              (0.111 * inData[1:rows-1,1:cols-1]) +
                              (0.111 * inData[1:rows-1,2:cols]) + 
                              (0.111 * inData[2:rows,0:cols-2]) +
                              (0.111 * inData[2:rows,1:cols-1]) + 
                              (0.111 * inData[2:rows,2:cols]))

# outData[1:rows-1,1:cols-1] = ((-1.0 * inData[0:rows-2,0:cols-2]) +
#                               (-1.0 * inData[0:rows-2,1:cols-1]) +
#                               (-1.0 * inData[0:rows-2,2:cols]) +
#                               (-1.0 * inData[1:rows-1,0:cols-2]) + 
#                               ( 8.0 * inData[1:rows-1,1:cols-1]) +
#                               (-1.0 * inData[1:rows-1,2:cols]) + 
#                               (-1.0 * inData[2:rows,0:cols-2]) +
#                               (-1.0 * inData[2:rows,1:cols-1]) + 
#                               (-1.0 * inData[2:rows,2:cols]))


# create the output image
driver = inDs.GetDriver()
outDs = driver.Create('lowpass3.img', cols, rows, 1, GDT_Float32)#GDT_CInt32
if outDs is None:
  print ('Could not create highpass3.img')
  sys.exit(1)
outBand = outDs.GetRasterBand(1)

# write the output data
outBand.WriteArray(outData, 0, 0)

# flush data to disk, set the NoData value and calculate stats
outBand.FlushCache()
stats = outBand.GetStatistics(0, 1)

# georeference the image and set the projection
outDs.SetGeoTransform(inDs.GetGeoTransform())
outDs.SetProjection(inDs.GetProjection())



print (time.time() - start, 'seconds')

plt.subplot(121)
plt.imshow(inData,cmap='gray')

plt.subplot(122)
plt.imshow(outData,cmap='gray')

plt.savefig("res3.png")
inDs = None
outDs = None
0.4882187843322754 seconds

在这里插入图片描述

Projecting rasters
设置栅格投影
from osgeo import gdal, osr 
from osgeo.gdalconst import *
import time
import matplotlib.pyplot as plt 

start = time.time()

#获取源数据及栅格信息
gdal.AllRegister()
src_data = gdal.Open("smallaster.img")
#获取源的坐标信息
srcSRS_wkt=src_data.GetProjection()
srcSRS=osr.SpatialReference()
srcSRS.ImportFromWkt(srcSRS_wkt)
#print("原数据空间参考:",srcSRS)
#获取栅格尺寸
src_width = src_data.RasterXSize
src_height = src_data.RasterYSize
src_count=src_data.RasterCount
#print("原数据图像信息:\n",src_width,src_height,src_count)
#获取源图像的仿射变换参数
src_trans=src_data.GetGeoTransform()

#左上角空间坐标
OriginLX_src=src_trans[0]
OriginTY_src=src_trans[3]
# 像素比
pixl_w_src=src_trans[1]
pixl_h_src=src_trans[5]
# 右下角坐标
OriginRX_src=OriginLX_src+pixl_w_src*src_width
OriginBY_src=OriginTY_src+pixl_h_src*src_height
#创建输出图像
driver = gdal.GetDriverByName("GTiff")
driver.Register()
dst_data = driver.Create("tpix1.tif",src_width,src_height,src_count)

#设置输出图像的空间参考WGS84
dstSRS=osr.SpatialReference()
dstSRS.ImportFromEPSG(4326)
#投影转换
ct=osr.CoordinateTransformation(srcSRS,dstSRS)
#计算目标影像的左上和右下坐标,即目标影像的仿射变换参数
OriginLX_dst,OriginTY_dst,temp=ct.TransformPoint(OriginLX_src,OriginTY_src)
OriginRX_dst,OriginBY_dst,temp=ct.TransformPoint(OriginRX_src,OriginBY_src)
 
pixl_w_dst=(OriginRX_dst-OriginLX_dst)/src_width
pixl_h_dst=(OriginBY_dst-OriginTY_dst)/src_height

dst_trans=[OriginLX_dst,pixl_w_dst,0,OriginTY_dst,0,pixl_h_dst]
#
dstSRS_wkt=dstSRS.ExportToWkt()
#设置仿射变换系数及投影
dst_data.SetGeoTransform(dst_trans)
dst_data.SetProjection(dstSRS_wkt)
#重新投影
gdal.ReprojectImage(src_data,dst_data,srcSRS_wkt,dstSRS_wkt,GRA_Bilinear)
print (time.time() - start, 'seconds')
#创建四级金字塔
#gdal.SetConfigOption('HFA_USE_RRD', 'YES')
#dst_data.BuildOverviews(overviewlist=[2,4,8,16])
#计算统计值
# for i in range(0,src_count):
#     band=dst_data.GetRasterBand(i+1)
#     band.SetNoDataValue(-99)
#     print (band.GetStatistics(0,1))

# read the input data
inBand = src_data.GetRasterBand(1)
inData = inBand.ReadAsArray(0, 0, src_width,src_height).astype(np.uint32)
plt.subplot(121)
plt.imshow(inData)

inBand = dst_data.GetRasterBand(1)
dstData = inBand.ReadAsArray(0, 0, src_width,src_height).astype(np.uint32)
plt.subplot(122)
plt.imshow(dstData)
1.7203800678253174 seconds
from osgeo import gdal, osr 
from osgeo.gdalconst import *
import numpy as np
import time

start = time.time()

#获取源数据及栅格信息
gdal.AllRegister()
src_data = gdal.Open("smallaster.img")
#获取源的坐标信息
srcSRS_wkt=src_data.GetProjection()
srcSRS=osr.SpatialReference()
srcSRS.ImportFromWkt(srcSRS_wkt)
#print("原数据空间参考:",srcSRS)
#获取栅格尺寸
src_width = src_data.RasterXSize
src_height = src_data.RasterYSize
src_count=src_data.RasterCount
#print("原数据图像信息:\n",src_width,src_height,src_count)
#获取源图像的仿射变换参数
src_trans=src_data.GetGeoTransform()

#左上角空间坐标
OriginLX_src=src_trans[0]
OriginTY_src=src_trans[3]
# 像素比
pixl_w_src=src_trans[1]
pixl_h_src=src_trans[5]
# 右下角坐标
OriginRX_src=OriginLX_src+pixl_w_src*src_width
OriginBY_src=OriginTY_src+pixl_h_src*src_height
#创建输出图像
driver = gdal.GetDriverByName("GTiff")
driver.Register()
dst_data = driver.Create("tpix2.tif",src_width,src_height,src_count)

for i in range(src_count):
    inBand = src_data.GetRasterBand(i+1)
    inData = inBand.ReadAsArray(0, 0, src_width, src_height).astype(np.uint32)
    outBand = dst_data.GetRasterBand(i+1)
    outBand.WriteArray(inData, 0, 0)# write the output data
    outBand.FlushCache()
    stats = outBand.GetStatistics(0, 1)
    inData=None

#设置输出图像的空间参考WGS84
dstSRS=osr.SpatialReference()
dstSRS.ImportFromEPSG(4326)
#投影转换
ct=osr.CoordinateTransformation(srcSRS,dstSRS)
#计算目标影像的左上和右下坐标,即目标影像的仿射变换参数
OriginLX_dst,OriginTY_dst,temp=ct.TransformPoint(OriginLX_src,OriginTY_src)
OriginRX_dst,OriginBY_dst,temp=ct.TransformPoint(OriginRX_src,OriginBY_src)
 
pixl_w_dst=(OriginRX_dst-OriginLX_dst)/src_width
pixl_h_dst=(OriginBY_dst-OriginTY_dst)/src_height

dst_trans=[OriginLX_dst,pixl_w_dst,0,OriginTY_dst,0,pixl_h_dst]
#
dstSRS_wkt=dstSRS.ExportToWkt()
#设置仿射变换系数及投影
dst_data.SetGeoTransform(dst_trans)
dst_data.SetProjection(dstSRS_wkt)
print (time.time() - start, 'seconds')
#重新投影
#gdal.ReprojectImage(src_data,dst_data,srcSRS_wkt,dstSRS_wkt,GRA_Bilinear)
#创建四级金字塔
#gdal.SetConfigOption('HFA_USE_RRD', 'YES')
#dst_data.BuildOverviews(overviewlist=[2,4,8,16])
#计算统计值
# for i in range(0,src_count):
#     band=dst_data.GetRasterBand(i+1)
#     band.SetNoDataValue(-99)
#     print (band.GetStatistics(0,1))

0.31161069869995117 seconds
Method comparison
比较运算
# homework 6b
# low-pass filter using slice notation
import os, time,sys
import numpy as np

from osgeo import gdal
from osgeo.gdalconst import *

import matplotlib.pyplot as plt

start = time.time()

# register all of the GDAL drivers
gdal.AllRegister()

# open the image
inDs = gdal.Open('dem.tiff', GA_ReadOnly)
if inDs is None:
  print ('Could not dem.tiff')
  sys.exit(1)

# get image size
rows = inDs.RasterYSize
cols = inDs.RasterXSize
nbands = inDs.RasterCount
print(rows,cols,nbands)
# read the input data
inBand = inDs.GetRasterBand(1)
inData = inBand.ReadAsArray(0, 0, cols, rows).astype(np.uint32)

plt.figure(figsize=(10,10))
plt.subplot(141)
plt.imshow(inData,cmap='gray')
plt.title("all")

outData = np.zeros((rows, cols), np.uint32)
outData1 = np.greater(inData, 1000)

plt.subplot(142)
plt.imshow(outData1,cmap='gray')
plt.title("elev>1000")

outData2= np.where((inData < 1000) & ( inData > 500), 1, 0)

plt.subplot(143)
plt.imshow(outData2,cmap='gray')
plt.title("elev>500 & elev <1000")

plt.savefig("res4.png")
324 368 1

在这里插入图片描述
参考文档 :

  • Geoprocessing with Python using Open Source GIS(https://www.gis.usu.edu/~chrisg/python/2009/)
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Although I’d taken a lot of programming classes in college, I never fully appreciated programming until I had a job that involved a lot of repetitive tasks. After amusing myself by automating much of that job, I decided to return to school and study biol- ogy, which is when I took my first GIS course. I was instantly in love, and managed to convince someone to give me a biology degree for writing an extension for ArcView GIS (a precursor to A rc GIS , for you Esri fans out there). After finishing that up, I went to work for the Remote Sensing/Geographic Information Systems Laboratory at Utah State University. One of my first projects involved some web mapping, and I soon became a big fan of the open source UMN M ap S erver software. That was my introduc- tion to open source geospatial software, including GDAL . I’m fairly certain that I didn’t appreciate the power of the GDAL/OGR library when I first learned about it, but I came to my senses once I started using it in my C++ and C# code. In the College of Natural Resources, there weren’t many people around who were interested in coding, but I did get to point people to the GDAL command-line utilities on a regular basis. But then Esri introduced Python as the scripting language of choice for A rc GIS , and things started to change. I don’t think I had used Python much before then, but playing with arcgisscripting (the original Esri Python module) made me realize how much I enjoyed working with Python, so naturally I had to start using GDAL with it as well. More importantly for this book, my coworker John Lowry suggested that we team- teach a Python-for- GIS class. He taught students how to use Python with A rc GIS , and I taught them about GDAL . The class turned out to be popular, so we taught it that way for another few years until John moved away. I took over the entire class and have been teaching it in various configurations ever since. I’ve never bothered to take the class material from the first two years off the web, however, which is how Manning found me. They asked if I would write a book on using GDAL with Python. I’d never had the desire to write a book, so it took a bit of persuasion to convince me to do it. In the end, it was my love for teaching that won me over. I’ve discovered over the years that I really enjoy teaching, mostly because I love watching students incorporate what they’re learning into the rest of their work. This is especially true of graduate students, some of whom might not have completed their research in a timely manner (or at all) if they hadn’t learned how to write code. I know that these skills will continue to assist them throughout their careers, and my hope is that this book will provide the same help to you, no matter if you’re a student, professional, or a hobbyist. This is fun stuff, and I hope you enjoy it as much as I do!
Summary Geoprocessing with Python teaches you how to use the Python programming language, along with free and open source tools, to read, write, and process geospatial data. Purchase of the print book includes a free eBook in PDF, Kindle, and ePub formats from Manning Publications. About the Technology This book is about the science of reading, analyzing, and presenting geospatial data programmatically, using Python. Thanks to dozens of open source Python libraries and tools, you can take on professional geoprocessing tasks without investing in expensive proprietary packages like ArcGIS and MapInfo. The book shows you how. About the Book Geoprocessing with Python teaches you how to access available datasets to make maps or perform your own analyses using free tools like the GDAL, NumPy, and matplotlib Python modules. Through lots of hands-on examples, you’ll master core practices like handling multiple vector file formats, editing geometries, applying spatial and attribute filters, working with projections, and performing basic analyses on vector data. The book also covers how to manipulate, resample, and analyze raster data, such as aerial photographs and digital elevation models. What's Inside Geoprocessing from the ground up Read, write, process, and analyze raster data Visualize data with matplotlib Write custom geoprocessing tools Three additional appendixes available online About the Reader To read this book all you need is a basic knowledge of Python or a similar programming language. About the Author Chris Garrard works as a developer for Utah State University and teaches a graduate course on Python programming for GIS. Table of Contents Chapter 1 Introduction Chapter 2 Python basics Chapter 3 Reading and writing vector data Chapter 4 Working with different vector file formats Chapter 5 Filtering data with OGR Chapter 6 Manipulating geometries with OGR Chapter 7 Vector analysis with OGR Chapter 8 Using spatial reference systems Chapter 9 Reading and writing raster data Chapter 10 Working with raster data Chapter 11 Map algebra with NumPy and SciPy Chapter 12 Map classification Chapter 13 Visualizing data appendix A Installation appendix B References

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值