Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 19 additions & 1 deletion src/rasterstats/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -213,8 +213,26 @@ def gen_zonal_stats(
feature_stats['max'] = float(masked.max())
if 'mean' in stats:
feature_stats['mean'] = float(masked.mean())

stats_count = int(masked.count())
if 'count' in stats:
feature_stats['count'] = int(masked.count())
feature_stats['count'] = stats_count

if 'area' in stats:
if rast.src is not None:
cellsize = rast.src.res[0] * rast.src.res[1]
else:
cellsize = rast.affine.a * rast.affine.a
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
cellsize = rast.affine.a * rast.affine.a
cellsize = rast.affine.a * rast.affine.e

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cells size shouldn't be assumed to be square. It's very rare in practice to see rasters where a != e but it could happen

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you need the absolute value here: abs(rast.affine.a * rast.affine.e)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To be safe, I would recommend reprojecting to be sure. I implemented a utility function for this use-case here - https://github.com/WFP-VAM/prism-app/pull/893/files#diff-0e7a305eb2d7da6652444269a99141f2a18d2fb8ea0ddbc045cd6c5a16e2ee9bR104

feature_stats['area'] = stats_count * cellsize

if 'area_percent' in stats:
if rast.src is not None:
cellsize = rast.src.res[0] * rast.src.res[1]
else:
cellsize = rast.affine.a * rast.affine.a
feature_stats['area_percent'] = stats_count * cellsize / geom.area


# optional
if 'sum' in stats:
feature_stats['sum'] = float(masked.sum())
Expand Down
2 changes: 1 addition & 1 deletion src/rasterstats/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

DEFAULT_STATS = ['count', 'min', 'max', 'mean']
VALID_STATS = DEFAULT_STATS + \
['sum', 'std', 'median', 'majority', 'minority', 'unique', 'range', 'nodata', 'nan']
['sum', 'std', 'median', 'majority', 'minority', 'unique', 'range', 'nodata', 'nan', 'area', 'area_percent']
# also percentile_{q} but that is handled as special case


Expand Down