1

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.

1 Answer 1

0

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...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.