skywalker
skywalker

Reputation: 79

Point in Polygon in a numpy array

I am using skimage. I need to create a mask equal in area to an image. The mask will have a region which will hide part of the image. I am building it as in the sample below but this is very slow and am sure there is a pythonic way of doing it. Could anyone highlight this please?

Code am using presently:

import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import skimage as sk

sourceimage = './sample.jpg'

img = np.copy(io.imread(sourceimage, as_gray=True))

mask = np.full(img.shape, 1)
maskpolygon = [(1,200),(300,644),(625,490),(625,1)]

from shapely.geometry import Point
from shapely.geometry.polygon import Polygon

pgon = Polygon(maskpolygon)
for r in range(mask.shape[0]):
    for c in range(mask.shape[1]):
        p = Point(r,c)
        if pgon.contains(p):
            mask[r,c] = 0

Expected result is like (for a 9x9 image - but I am working on 700x700)

[1,1,1,1,1,1,1,1,1]
[1,1,1,1,1,1,1,1,1]
[1,1,0,0,1,1,1,1,1]
[1,1,0,0,1,1,1,1,1]
[1,1,0,0,0,0,1,1,1]
[1,1,0,0,0,0,0,1,1]
[1,1,1,0,0,0,0,1,1]
[1,1,1,1,0,0,1,1,1]
[1,1,1,1,1,1,1,1,1]

I can invert 1's and 0's to show/hide region.

Thank you.

Upvotes: 0

Views: 769

Answers (1)

skywalker
skywalker

Reputation: 79

I have been able to resolve this thanks to @HansHirse.

Below is how I worked it out

sourceimage = './sample.jpg'
figuresize = (100, 100)

from skimage.draw import polygon

#open source and create a copy
img = np.copy(io.imread(sourceimage, as_gray=True))

mask = np.full(img.shape, 0)
maskpolygon = [(1,1), (280,1),(625, 280),(460, 621),(15, 625)]

maskpolygonr = [x[0] for x in maskpolygon]
maskpolygonc = [x[1] for x in maskpolygon]
rr, cc = polygon(maskpolygonr, maskpolygonc)
mask[rr ,cc] = 1

masked_image = img * mask

# show step by step what is happening
fig, axs = plt.subplots(nrows = 3, ncols = 1, sharex=True, sharey = True, figsize=figuresize )

ax = axs.ravel()

ax[0].imshow(img)#, cmap=plt.cm.gray)
ax[1].imshow(mask)#, cmap=plt.cm.gray)
ax[2].imshow(masked_image)#, cmap=plt.cm.gray)

Upvotes: 1

Related Questions