[英]Type error: reading ESRI shapefile driver using OGR/GDAL in Python
[英]GTiff mask with shapefile in python with gdal, ogr, etc
好的,經過一些擺弄,我從第二個評論行的網站超鏈接調整了一個腳本。 該腳本的目的是使用帶有多個多邊形的shapefile(每個都帶有“Name”記錄)來剪切/屏蔽GTAW格式的LARGE柵格(即不能適合32位Python 2.7.5應用程序)並保存將柵格剪切到“剪輯”子目錄中,其中每個蒙版網格以每個多邊形的“名稱”命名。 與原始腳本一樣,它假設GTiff和shapefile在同一個投影中並且正確重疊,並且它處理~100個掩碼/秒。 但是,我已經修改了該腳本1)使用浮點值高程網格,2)只將較大網格的窗口加載到由當前多邊形限定的內存中(即減少內存負載),2)導出GTiff具有正確(即未移位)的地理位置和價值。
但是,我遇到了每個蒙版網格的問題,我稱之為“右側陰影”。 這是對於多邊形中的每條〜垂直線,其中該線的右側在給定多邊形之外,被遮罩的網格將包括該多邊形邊右側的一個柵格單元。
因此,我的問題是,我做錯了什么讓蒙面網格成為右陰影?
我將試圖弄清楚如何發布一個示例shapefile和tif,以便其他人可以重現。 下面的代碼還有整數值衛星圖像的注釋行(例如,如geospatialpython.com的原始代碼中所示)。
# RasterClipper.py - clip a geospatial image using a shapefile
# http://geospatialpython.com/2011/02/clip-raster-using-shapefile.html
# http://gis.stackexchange.com/questions/57005/python-gdal-write-new-raster-using-projection-from-old
import os, sys, time, Tkinter as Tk, tkFileDialog
import operator
from osgeo import gdal, gdalnumeric, ogr, osr
import Image, ImageDraw
def SelectFile(req = 'Please select a file:', ft='txt'):
""" Customizable file-selection dialogue window, returns list() = [full path, root path, and filename]. """
try: # Try to select a csv dataset
foptions = dict(filetypes=[(ft+' file','*.'+ft)], defaultextension='.'+ft)
root = Tk.Tk(); root.withdraw(); fname = tkFileDialog.askopenfilename(title=req, **foptions); root.destroy()
return [fname]+list(os.path.split(fname))
except: print "Error: {0}".format(sys.exc_info()[1]); time.sleep(5); sys.exit()
def rnd(v, N): return int(round(v/float(N))*N)
def rnd2(v): return int(round(v))
# Raster image to clip
rname = SelectFile('Please select your TIF DEM:',ft='tif')
raster = rname[2]
print 'DEM:', raster
os.chdir(rname[1])
# Polygon shapefile used to clip
shp = SelectFile('Please select your shapefile of catchments (requires Name field):',ft='shp')[2]
print 'shp:', shp
qs = raw_input('Do you want to stretch the image? (y/n)')
qs = True if qs == 'y' else False
# Name of base clip raster file(s)
if not os.path.exists('./clip/'): os.mkdir('./clip/')
output = "/clip/clip"
# This function will convert the rasterized clipper shapefile
# to a mask for use within GDAL.
def imageToArray(i):
"""
Converts a Python Imaging Library array to a
gdalnumeric image.
"""
a=gdalnumeric.fromstring(i.tostring(),'b')
a.shape=i.im.size[1], i.im.size[0]
return a
def arrayToImage(a):
"""
Converts a gdalnumeric array to a
Python Imaging Library Image.
"""
i=Image.fromstring('L',(a.shape[1],a.shape[0]), (a.astype('b')).tostring())
return i
def world2Pixel(geoMatrix, x, y, N= 5, r=True):
"""
Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
the pixel location of a geospatial coordinate
"""
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
yDist = geoMatrix[5]
rtnX = geoMatrix[2]
rtnY = geoMatrix[4]
if r:
pixel = int(round(x - ulX) / xDist)
line = int(round(ulY - y) / xDist)
else:
pixel = int(rnd(x - ulX, N) / xDist)
line = int(rnd(ulY - y, N) / xDist)
return (pixel, line)
def histogram(a, bins=range(0,256)):
"""
Histogram function for multi-dimensional array.
a = array
bins = range of numbers to match
"""
fa = a.flat
n = gdalnumeric.searchsorted(gdalnumeric.sort(fa), bins)
n = gdalnumeric.concatenate([n, [len(fa)]])
hist = n[1:]-n[:-1]
return hist
def stretch(a):
"""
Performs a histogram stretch on a gdalnumeric array image.
"""
hist = histogram(a)
im = arrayToImage(a)
lut = []
for b in range(0, len(hist), 256):
# step size
step = reduce(operator.add, hist[b:b+256]) / 255
# create equalization lookup table
n = 0
for i in range(256):
lut.append(n / step)
n = n + hist[i+b]
im = im.point(lut)
return imageToArray(im)
# Also load as a gdal image to get geotransform
# (world file) info
srcImage = gdal.Open(raster)
geoTrans_src = srcImage.GetGeoTransform()
#print geoTrans_src
pxs = int(geoTrans_src[1])
srcband = srcImage.GetRasterBand(1)
ndv = -9999.0
#ndv = 0
# Create an OGR layer from a boundary shapefile
shapef = ogr.Open(shp)
lyr = shapef.GetLayer()
minXl, maxXl, minYl, maxYl = lyr.GetExtent()
ulXl, ulYl = world2Pixel(geoTrans_src, minXl, maxYl)
lrXl, lrYl = world2Pixel(geoTrans_src, maxXl, minYl)
#poly = lyr.GetNextFeature()
for poly in lyr:
pnm = poly.GetField("Name")
# Convert the layer extent to image pixel coordinates
geom = poly.GetGeometryRef()
#print geom.GetEnvelope()
minX, maxX, minY, maxY = geom.GetEnvelope()
geoTrans = geoTrans_src
ulX, ulY = world2Pixel(geoTrans, minX, maxY)
lrX, lrY = world2Pixel(geoTrans, maxX, minY)
# Calculate the pixel size of the new image
pxWidth = int(lrX - ulX)
pxHeight = int(lrY - ulY)
# Load the source data as a gdalnumeric array
#srcArray = gdalnumeric.LoadFile(raster)
clip = gdalnumeric.BandReadAsArray(srcband, xoff=ulX, yoff=ulY, win_xsize=pxWidth, win_ysize=pxHeight)
#clip = srcArray[:, ulY:lrY, ulX:lrX]
# Create a new geomatrix for the image
geoTrans = list(geoTrans)
geoTrans[0] = minX
geoTrans[3] = maxY
# Map points to pixels for drawing the
# boundary on a blank 8-bit,
# black and white, mask image.
points = []
pixels = []
#geom = poly.GetGeometryRef()
pts = geom.GetGeometryRef(0)
for p in range(pts.GetPointCount()):
points.append((pts.GetX(p), pts.GetY(p)))
for p in points:
pixels.append(world2Pixel(geoTrans, p[0], p[1]))
rasterPoly = Image.new("L", (pxWidth, pxHeight), 1)
rasterize = ImageDraw.Draw(rasterPoly)
rasterize.polygon(pixels, 0)
mask = imageToArray(rasterPoly)
# Clip the image using the mask
#clip = gdalnumeric.choose(mask, (clip, 0)).astype(gdalnumeric.uint8)
clip = gdalnumeric.choose(mask, (clip, ndv)).astype(gdalnumeric.numpy.float)
# This image has 3 bands so we stretch each one to make them
# visually brighter
#for i in range(3):
# clip[i,:,:] = stretch(clip[i,:,:])
if qs: clip[:,:] = stretch(clip[:,:])
# Save ndvi as tiff
outputi = rname[1]+output+'_'+pnm+'.tif'
#gdalnumeric.SaveArray(clip, outputi, format="GTiff", prototype=srcImage)
driver = gdal.GetDriverByName('GTiff')
DataSet = driver.Create(outputi, pxWidth, pxHeight, 1, gdal.GDT_Float64)
#DataSet = driver.Create(outputi, pxWidth, pxHeight, 1, gdal.GDT_Int32)
DataSet.SetGeoTransform(geoTrans)
Projection = osr.SpatialReference()
Projection.ImportFromWkt(srcImage.GetProjectionRef())
DataSet.SetProjection(Projection.ExportToWkt())
# Write the array
DataSet.GetRasterBand(1).WriteArray(clip)
DataSet.GetRasterBand(1).SetNoDataValue(ndv)
# Save ndvi as an 8-bit jpeg for an easy, quick preview
#clip = clip.astype(gdalnumeric.uint8)
#gdalnumeric.SaveArray(clip, rname[1]+outputi+'.jpg', format="JPEG")
#print '\t\tSaved:', outputi, '-.tif, -.jpg'
print 'Saved:', outputi
del mask, clip, geom
del driver, DataSet
del shapef, srcImage, srcband
此功能已合並到gdal命令行實用程序中。 鑒於你的情況,我沒有看到任何你想在Python中自己做的原因。
您可以使用OGR循環遍歷幾何,並使用適當的參數為每個調用gdalwarp
。
import ogr
import subprocess
inraster = 'NE1_HR_LC_SR_W_DR\NE1_HR_LC_SR_W_DR.tif'
inshape = '110m_cultural\ne_110m_admin_0_countries_lakes.shp'
ds = ogr.Open(inshape)
lyr = ds.GetLayer(0)
lyr.ResetReading()
ft = lyr.GetNextFeature()
while ft:
country_name = ft.GetFieldAsString('admin')
outraster = inraster.replace('.tif', '_%s.tif' % country_name.replace(' ', '_'))
subprocess.call(['gdalwarp', inraster, outraster, '-cutline', inshape,
'-crop_to_cutline', '-cwhere', "'admin'='%s'" % country_name])
ft = lyr.GetNextFeature()
ds = None
我在上面的例子中使用了來自Natural Earth的一些示例數據,對於巴西,切口看起來像:
如果您只想將圖像裁剪到多邊形區域並且不遮擋任何外部區域,則可以變換Shapefile,使其包含多邊形的包絡。 或者干脆松shape文件並調用gdal_translate
與-projwin
指定感興趣的區域。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.