0

I want to count the no data values, because when I loaded them with rioxarray they seemed to be oddly many pixel to be non-valid.

When I open the given file in qgis the valid pixel percentage is 89.6 %.

My attempt to measure it with raster was:

import rioxarray as rxa
import numpy as np

raster = rxa.open_rasterio("Z:/path/to/test.tif")
data = raster.data
print(np.sum(data == raster.rio.nodata) /data.size * 100)

output: 10.122128919010978

Background: I wanted to use numpy masked arrays and mask the e.g. the nodata, black pixels, or values above a threshold. But when I use this method, to mask the nodata pixels, almost everypixel is getting masked.

2 Answers 2

1

Using the following you can check if this is what you want:

# Import Libraries
import rasterio as rio
import numpy as np
import pandas as pd

# Open Raster Dataset with Rasterio
with rio.open('path to your raster') as src:
    no_data = src.nodata # Get Raster No-Data value
    img = src.read(1) # Read Image as Numpy Array

# Get unique Pixel Values & their Count in numpy array    
unique, count = np.unique(img, return_counts = True)

# Defining a new pandas dataframe and adding the Numpy Array to the dataframe    
raster_dataframe = pd.DataFrame()
raster_dataframe['Pixel Value'] = unique
raster_dataframe['Count'] = count

# Compute sum of all values in the 'Count' Column of the dataframe 
sum_count = raster_dataframe['Count'].sum()

# Get the dataframe row where 'Pixel Value' is 'no_data'
search = raster_dataframe.loc[raster_dataframe['Pixel Value'] == no_data]

# Caculating the percentage of No-Data Pixels
percentage_no_data = (search['Count'].values[0]/sum_count) * 100
1
  • Could you add some comments and explanations? That will help beginners a lot :) THanks! Commented Dec 17, 2020 at 11:04
0

For rioxarray you would want something like this:

import rioxarray as rxa

rds = rxa.open_rasterio("Z:/path/to/test.tif", masked=True)

valid_px_count = int(rds.count().compute())
total_px_count = rds.size

nodata_px_count = total_px_count - valid_px_count

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.