Coverage for hml/sumImageWithinCircle.py: 4%
23 statements
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-23 08:31 +0000
« prev ^ index » next coverage.py v7.8.1, created at 2025-05-23 08:31 +0000
1#!/usr/bin/env python3
3# Define function ...
4def sumImageWithinCircle(img, xmin, xmax, ymin, ymax, r, /, *, cx = 0.0, cy = 0.0, ndiv = 16):
5 """
6 Sum the pixel values on an image that are within a hard circular mask.
8 Arguments:
9 img -- 2D image with axes (ny, nx)
10 xmin -- left edge of leftmost pixel
11 xmax -- right edge of rightmost pixel
12 ymin -- lower edge of lowermost pixel
13 ymax -- upper edge of uppermost pixel
14 r -- radius of circle
16 Keyword arguments:
17 cx -- x position of centre of circle (default 0.0)
18 cy -- y position of centre of circle (default 0.0)
19 ndiv -- number sub-divisions (default 16)
21 Note:
22 This function is crying out for FORTRAN+OpenMP.
23 """
25 # Import special modules ...
26 try:
27 import numpy
28 except:
29 raise Exception("\"numpy\" is not installed; run \"pip install --user numpy\"") from None
31 # Import sub-functions ...
32 from .findFractionOfPixelWithinCircle import findFractionOfPixelWithinCircle
34 # Create nodes relative to the centre of the circle ...
35 xaxis = numpy.linspace(xmin, xmax, num = img.shape[1] + 1) - cx
36 yaxis = numpy.linspace(ymin, ymax, num = img.shape[0] + 1) - cy
38 # Find out the distance of each node to the centre of the circle ...
39 dist = numpy.zeros((yaxis.size, xaxis.size), dtype = numpy.float64)
40 for ix in range(xaxis.size):
41 for iy in range(yaxis.size):
42 dist[iy, ix] = numpy.hypot(xaxis[ix], yaxis[iy])
44 # Initialize total ...
45 tot = 0.0
47 # Loop over x-axis ...
48 for ix in range(img.shape[1]):
49 # Loop over y-axis ...
50 for iy in range(img.shape[0]):
51 # Skip this pixel if it is empty ...
52 if img[iy, ix] == 0.0:
53 continue
55 # Skip this pixel if it is all outside of the circle ...
56 if numpy.all(dist[iy:iy + 2, ix:ix + 2] >= r):
57 continue
59 # Check if this pixel is entirely within the circle or if it
60 # straddles the circumference ...
61 if numpy.all(dist[iy:iy + 2, ix:ix + 2] <= r):
62 # Add all of the value to total ...
63 tot += img[iy, ix]
64 else:
65 # Add part of the value to total ...
66 tot += img[iy, ix] * findFractionOfPixelWithinCircle(
67 xaxis[ix],
68 xaxis[ix + 1],
69 yaxis[iy],
70 yaxis[iy + 1],
71 r,
72 cx = 0.0,
73 cy = 0.0,
74 ndiv = ndiv,
75 )
77 # Return answer ...
78 return tot