ZonalStatistics.gh (10.4 KB)
I’m writing a script to read an image and then calculate statistics per polygon overlaid on top of the image. The script I’ve attached works, but being that I’m relatively new to C#, I know it could be much faster. Right now the script I’ve posted spits out the average red value for all the pixels in reach polygon. Feel free to use the attached image with the script.
Here’s the process:
- Create a grid of rectangles overlaid on top of the image based on the dimensions of the image
- Create a list of doubles for each rectangle (as one nested list). Each list will store the red values for the pixels inside the intersecting rectangle.
- Read each pixel and in its place create a point where the x and y values correspond to the pixel location and the z-value corresponds to the red value of that pixel.
- Create a boolean for each point (set to false) to determine whether that point has already been “found” or accounted for inside a rectangle. No point is inside two rectangles, since they form a perfect grid with no overlap.
- Run a nested for-loop determining which points are inside which rectangles. Right now I’m creating a bounding box for each rectangle, and checking whether the x and y values of each point fall inside the bounding box Min and Max values for x and y. I found this method faster than using Point Containment. If the point is found inside that rectangle, the boolean for that point is set to “true” so the point will not be considered for future rectangles.
- For each list of red values, calculate the average (or other statistics, as need be).
Thanks, everyone! I sense that creating a point and testing point containment is probably not the fastest way to run statistics on pixel values, but am not sure how to proceed. I’m eager to learn more advanced methods and optimize this script.