2

I need to get rid of the border points in an array which came from a raster. I first converted my GeoTiff to numpy array using:

input = gdal.Open("file.tif")
array = np.array(input.GetRasterBand(1).ReadAsArray())

Then I want to remove the boundary pixels, so that one column and one row (so two of each totaling four lines) are subtracted in the final array. This is because I need to keep applying functions which cannot use these boundary pixels. So I did the following:

window = []
for row in range(1):
    for col in range(1):
        window.append(array[row:(array.shape[0] - 2), col:(array.shape[1] - 2)])

Next I converted this new list into a numpy array via newarray = np.array(window)

Originally I had a total of points = 140, with 14 rows and 10 columns. And if I print the newarray to the console my new total is 96 points, which is expected. But if I check the number of rows and columns in this new array via

print newarray.shape[0], newarray.shape[1]

then my resulting structure shows that I only have 1 row and 12 columns. How does this make sense? I should have 12 rows and 8 columns... Is the formula for getting rid of the bounding pixels incorrect, or is there a different and more efficient way to do this and remove the bordering pixels from each side of the array?

1 Answer 1

2

You can do that, only in one path, with 'ReadAsArray' method of GDAL Python module. Complete code is:

from osgeo import gdal

driver = gdal.GetDriverByName('GTiff')
filename = "/home/zeito/pyqgis_data/file.tif"

dataset = gdal.Open(filename)
band = dataset.GetRasterBand(1)

cols = dataset.RasterXSize
rows = dataset.RasterYSize

print rows, cols

data = band.ReadAsArray(1, 1, cols-2, rows-2)

print data

dataset = None

To test the code, I created one random raster (values between 1 and 10) with 14 rows and 10 columns; as it can be observed at next image:

enter image description here

After running the code, at the Python Console of QGIS was printed the array without border pixels values in the original raster. These values in the resulting array were corroborated with Value Tool plugin. They were produced as expected.

enter image description here

1
  • You are awesome. That was actually quite simple. Thanks for all your help! :)
    – spartmar
    Commented Aug 4, 2016 at 23:42

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.