1

例Clip a Raster using a Shapefileに従って、ポリゴン (シェープファイル、*.shp) を使用してラスター イメージ (Erdas Imagine Images、*.img) をクリッピングしています。例に従って、エラーがあります:

Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: too many indices

このエラーは投稿のコメント内でも報告されていますが、解決策は報告されていません。このリンクデータを使用すると、例で使用したデータをダウンロードできます。16ビットイメージで作業している間、イメージは8ビットです。おそらくエラーの原因はこの違いです(8bit vs 16 bit)

import osgeo.gdal
from osgeo import gdal, gdalnumeric, ogr, osr
import numpy as np

def world2Pixel(geoMatrix, x, y):
    """
    Uses a gdal geomatrix (gdal.GetGeoTransform()) to calculate
    the pixel location of a geospatial coordinate
    (source http://www2.geog.ucl.ac.uk/~plewis/geogg122/vectorMask.html)
    geoMatrix
    [0] = top left x (x Origin)
    [1] = w-e pixel resolution (pixel Width)
    [2] = rotation, 0 if image is "north up"
    [3] = top left y (y Origin)
    [4] = rotation, 0 if image is "north up"
    [5] = n-s pixel resolution (pixel Height)

    """
    ulX = geoMatrix[0]
    ulY = geoMatrix[3]
    xDist = geoMatrix[1]
    yDist = geoMatrix[5]
    rtnX = geoMatrix[2]
    rtnY = geoMatrix[4]
    pixel = np.round((x - ulX) / xDist).astype(np.int)
    line = np.round((ulY - y) / xDist).astype(np.int)
    return (pixel, line)

inFile = 'C:\\myimage.img'
poly = "C:\\ClipArea.shp"

# Open the image as a read only image
ds = osgeo.gdal.Open(inFile,gdal.GA_ReadOnly)
# Check the ds (=dataset) has been successfully open
# otherwise exit the script with an error message.
if ds is None:
    raise SystemExit("The raster could not openned")
# Get image georeferencing information.
geoMatrix = ds.GetGeoTransform()
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
yDist = geoMatrix[5]
# Get image georeferencing information.
geoMatrix = ds.GetGeoTransform()
ulX = geoMatrix[0]
ulY = geoMatrix[3]
xDist = geoMatrix[1]
yDist = geoMatrix[5]
# open shapefile (= border of are of interest)
shp = osgeo.ogr.Open(poly)
if not len(shp) is 1:
    print "The shapefile with more than 1 record"
    sys.exit(-1)
source_shp = ogr.GetDriverByName("Memory").CopyDataSource(shp, "")
# Create an OGR layer from a boundary shapefile
source_layer = source_shp.GetLayer(0)
# Convert the layer extent to image pixel coordinates
minX, maxX, minY, maxY = source_layer.GetExtent()
ulX, ulY = world2Pixel(geoMatrix, minX, maxY)
lrX, lrY = world2Pixel(geoMatrix, 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(inFile)
clip = srcArray[:, ulY:lrY, ulX:lrX]

**Traceback (most recent call last):
  File "<interactive input>", line 1, in <module>
IndexError: too many indices**
4

0 に答える 0