13

I have a code that slices a numpy array into a circle. I wish to recover only the values included in a certain range of angles from the circle and mask the array. For example: mask the original array with the (x,y) positions comprised between 0 and 45 degrees of the circle.

Is there a pythonic way for doing so?

Here's my (simplified) original code:

import numpy as np
matrix = np.zeros((500,500))
x = 240
y = 280
radius = 10
mask=np.ogrid[x-radius:x+radius+1,y-radius:y+radius+1]
matrix[mask]

Thanks in advance

Edit: I omitted that radius can vary.

ali_m
  • 71,714
  • 23
  • 223
  • 298
Guadancil11
  • 625
  • 3
  • 8
  • 16

2 Answers2

31

I would do this by converting from cartesian to polar coordinates and constructing boolean masks for the circle and for the range of angles you want:

import numpy as np

def sector_mask(shape,centre,radius,angle_range):
    """
    Return a boolean mask for a circular sector. The start/stop angles in  
    `angle_range` should be given in clockwise order.
    """

    x,y = np.ogrid[:shape[0],:shape[1]]
    cx,cy = centre
    tmin,tmax = np.deg2rad(angle_range)

    # ensure stop angle > start angle
    if tmax < tmin:
            tmax += 2*np.pi

    # convert cartesian --> polar coordinates
    r2 = (x-cx)*(x-cx) + (y-cy)*(y-cy)
    theta = np.arctan2(x-cx,y-cy) - tmin

    # wrap angles between 0 and 2*pi
    theta %= (2*np.pi)

    # circular mask
    circmask = r2 <= radius*radius

    # angular mask
    anglemask = theta <= (tmax-tmin)

    return circmask*anglemask

For example:

from matplotlib import pyplot as pp
from scipy.misc import lena

matrix = lena()
mask = sector_mask(matrix.shape,(200,100),300,(0,50))
matrix[~mask] = 0
pp.imshow(matrix)
pp.show()

enter image description here

ali_m
  • 71,714
  • 23
  • 223
  • 298
  • 1
    @ali_m +1. I hope you don't mind, I added the picture into the answer so we can see exactly what is going on. – Hooked Aug 21 '13 at 13:25
  • 2
    `theta = np.arctan2(x-cx,y-cy)` must be changed into all positive angles using `theta = np.where(theta<0,2*pi+theta,theta)` otherwise the code above will not work correctly for angles higher than 180. – Developer Aug 21 '13 at 13:52
  • @Developer well spotted, I've edited my function to address this case – ali_m Aug 21 '13 at 13:59
1

Same approach for centered circles in square matrices:

def circleMask(mat, r=0):
    if mat.shape[0] != mat.shape[1]:
        raise TypeError('Matrix has to be square')
    if not isinstance(r, int):
        raise TypeError('Radius has to be of type int')

    s = mat.shape[0]
    d = num.abs(num.arange(-s/2 + s%2, s/2 + s%2))
    dm = num.sqrt(d[:, num.newaxis]**2 + d[num.newaxis, :]**2)

    return num.logical_and(dm >= r-.5, dm < r+.5)

looping over this implicit function is costly!

n1nj4
  • 511
  • 5
  • 13