Search code examples
pythonimageclassgdal

Construct class for gdal open


I an very new to python (2.6) and have a simple function to open geotif using gdal. It returns image array and image size (x,y).

def gdal_open(raster_file):

    if type(raster_file) is str and os.path.isfile(raster_file):
        gd_img = gdal.Open(raster_file)
        img_x = gd_img.RasterXSize # column
        img_y = gd_img.RasterYSize # row
        img = gd_img.ReadAsArray(0, 0, img_x, img_y)

    elif type(raster_file) is str and not os.path.isfile(raster_file):
        raise IOError

    return img, img_x, img_y

I want to convert this to class to get img, img.x and img.y as outputs. Can somebody help me?

Thanks, Jay


Solution

  • here is the class its name is IMG

    class IMG:

    def __init__(self,path):
        if type(path)==str and os.path.isfile(path):
            self.path=path
            self.Raster=gdal.Open(path)
        elif type(path)==str and not os.path.isfile(path):
            raise IOError
    
    def X(self):
        return self.Raster.RasterXSize
    
    def Y(self):
        return self.Raster.RasterYSize
    
    def RasterArray(self):
        return self.Raster.ReadAsArray()
    

    and to use it

    filepath="path/raster_name.tif"

    raster=IMG(filepath)

    xsize=raster.X()

    ysize=raster.Y()

    array=raster.RasterArray()