pythonmatlabfilteringmasking

Python equivalent of Matlab's createMask() function


I want to create a Python equivalent of a Matlab code that creates a filtering mask. In the Matlab version, I have a variable position that maintains xy values for a polygon which I am creating the mask from. Here is the Matlab version:

        ...        
        xlim([0 50])
        ylim([0 1000])
        h=gca;
        position = [0 0; ...
                    2.5 0; ...
                    10.01 75; ...
                    10.01 125; ...
                    0 25];
        pol= impoly(h, position);
        mask= createMask(pol);

I did not find an equivalent 'createMask' function in Python, and I want the mask to mimic the Matlab one.


Solution

  • You could use the Path class of matplotlib. It has a method called contains_points to give you a mask.

    Here is a minimal working example:

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib.patches import Polygon
    from matplotlib.path import Path
    
    # Define your polygon's vertices
    vertices = np.array([[0, 0], [2.5, 0], [10.01, 75], [10.01, 125], [0, 25]])
    
    # Create the polygon
    polygon = Polygon(vertices, closed=True, fill=None, edgecolor='none', facecolor='none')
    
    # Generate the masking filter
    x, y = np.meshgrid(np.arange(0, 50), np.arange(0, 1000))
    points = np.column_stack((x.ravel(), y.ravel()))
    path = Path(vertices)
    mask = path.contains_points(points).reshape(x.shape)
    
    # plot...