Python:以优雅的方式改进和代码保存函数,以避免几个if ... else语句

时间:2012-11-16 23:55:19

标签: python performance optimization if-statement

我写了以下功能。此函数读取* .las点格式并通过GDAL创建栅格网格图像。使用 dtype ,我可以选择GDAL description后面的栅格网格格式。我使用了几个if ... else语句,但我希望我的代码有一些建议,以便保存行,以便让我的功能更优雅

    if dtype == "GDT_Unknown": # Unknown or unspecified type
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Unknown)
    elif dtype == "GDT_Byte": # Eight bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Byte)
    elif dtype == "GDT_UInt16": # Sixteen bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_UInt16)
    elif dtype == "GDT_Int16": # Sixteen bit signed integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Int16)
    elif dtype == "GDT_UInt32": # Thirty two bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_UInt32)
    elif dtype == "GDT_Int32": # Thirty two bit signed integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Int32)
    elif dtype == "GDT_Float32": # Thirty two bit floating point
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Float32)
    elif dtype == "GDT_Float64": # Sixty four bit floating point
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Float64)
    elif dtype == "GDT_CInt16": # Complex Int16
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CInt16)
    elif dtype == "GDT_CInt32": # Complex Int32
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CInt32)
    elif dtype == "GDT_CFloat32": # Complex Float32
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CFloat32)
    elif dtype == "GDT_CFloat64": # Complex Float64
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CFloat64)

提前致谢

def LAS2MAXGrid(inFile,outFile,gridSize=1,dtype="GDT_Float32",nodata=-9999.00,BBOX=None,EPSG=None):
    if BBOX == None:
        X = []
        Y = []
        for p in lasfile.File(inFile,None,'r'):
            X.append(p.x)
            Y.append(p.y)
        xmax, xmin = max(X),min(X)
        ymax, ymin = max(Y), min(Y)
        del X,Y
    else:
        xmax,xmin,ymax,ymin = BBOX[0],BBOX[1],BBOX[2],BBOX[3]
    # number of row and columns
    nx = int(math.ceil(abs(xmax - xmin)/gridSize))
    ny = int(math.ceil(abs(ymax - ymin)/gridSize))
    # Create an array to hold the values
    data = np.zeros((ny, nx))
    # read all points line-by-line
    for p in lasfile.File(inFile,None,'r'):
        # Compute the x and y offsets for where this point would be in the raster
        dx = int((p.x - xmin)/gridSize)
        dy = int((ymax - p.y)/gridSize)
        if data[dy,dx] >= p.z:
            data[dy,dx] = data[dy,dx]
        elif data[dy,dx] < p.z:
            # Add the z value for that pixel
            data[dy,dx] = p.z
    # Replacing values equal than a limit in a numpy array
    np.putmask(data, data == 0.00,nodata)
     # Create gtif
    if dtype == "GDT_Unknown": # Unknown or unspecified type
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Unknown)
    elif dtype == "GDT_Byte": # Eight bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Byte)
    elif dtype == "GDT_UInt16": # Sixteen bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_UInt16)
    elif dtype == "GDT_Int16": # Sixteen bit signed integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Int16)
    elif dtype == "GDT_UInt32": # Thirty two bit unsigned integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_UInt32)
    elif dtype == "GDT_Int32": # Thirty two bit signed integer
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Int32)
    elif dtype == "GDT_Float32": # Thirty two bit floating point
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Float32)
    elif dtype == "GDT_Float64": # Sixty four bit floating point
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_Float64)
    elif dtype == "GDT_CInt16": # Complex Int16
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CInt16)
    elif dtype == "GDT_CInt32": # Complex Int32
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CInt32)
    elif dtype == "GDT_CFloat32": # Complex Float32
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CFloat32)
    elif dtype == "GDT_CFloat64": # Complex Float64
        target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.GDT_CFloat64)
    # top left x, w-e pixel resolution, rotation, top left y, rotation, n-s pixel resolution
    target_ds.SetGeoTransform((xmin, gridSize, 0,ymax, 0, -gridSize))
    # set the reference info
    if EPSG is None:
        # Source has no projection (needs GDAL >= 1.7.0 to work)
        target_ds.SetProjection('LOCAL_CS["arbitrary"]')
    else:
        proj = osr.SpatialReference()
        proj.ImportFromEPSG(EPSG)
        # Make the target raster have the same projection as the source
        target_ds.SetProjection(proj.ExportToWkt())
    # write the band
    target_ds.GetRasterBand(1).WriteArray(data)
    target_ds.GetRasterBand(1).SetNoDataValue(nodata)
    target_ds = None

3 个答案:

答案 0 :(得分:4)

您可以尝试这样的事情:

dtypes = {
    "GDT_Unknown": gdal.GDT_Unknown,
    "GDT_Byte": gdal.GDT_Byte, 
    # etc
}

target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, dtypes[dtype])

答案 1 :(得分:2)

由于您的dtype变量名称与您尝试使用的gdal变量的名称相匹配,因此这样的内容应该可以正常使用。

target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, gdal.__getattribute__(dtype))

答案 2 :(得分:1)

这个单行怎么样:

target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, getattr(gdal, dtype))

如果不希望'dtype'值

,你也可以将它包装在try / catch语句中
try:
    target_ds = gdal.GetDriverByName('GTiff').Create(outFile, nx,ny, 1, getattr(gdal, dtype))
except:
    target_ds = None

编辑:抱歉Esthete,并不是要复制你的答案,当我开始回复你的帖子时不在那里.. :(