If you're doing this operation only once for an image, you can determine while looping with pointers if a color is in the desired area or not and build the list then group or even build the histogram directly. If you would be doing the operation many times for an image, you can build the list the same way you're doing it once then later filter the elements based on the color index in the list using this Where overload[^] before doing the grouping. To know if an index is in an area
xI = index % width
yI = index % height
xI >= x1 &&
yI >= y1 &&
xI <= x2 &&
yI <= y2
that (x1, y1) is the top-left pixel of the area
and (x2, y2) is the bottom-right pixel of the area
A faster method is to determine the index corresponding to the top-left pixel the loop over the list elements inside the area and build the histogram directly (or build an array and group but this is slower and requires more memory).
Eslam Afifi