3

I need to draw a 2D binary mask based on array of vertexes of N convex polygons.

import numpy as np

mask = np.zeros((100, 100), dtype=np.int8)

polys = np.array([[[30,32], [36,46], [41,48], [50, 36]],
                  [[10,32], [16,46], [30,48], [40, 36]],
                  [[56,44], [58,70], [78,90], [75,34]]], np.int32)

Area of intersection between polygons should be also masked. I know how to implement it using cv2 library:

import cv2 

for i in polys.tolist():
    cv2.fillConvexPoly(mask, np.array(i), 1)

imshow(mask, cmap='gray')

Draw multiple convex polygons using opencv

But I cannot figure out how to do that using native numpy operations (without for loops) to reduce time to run the function.

Divakar
  • 218,885
  • 19
  • 262
  • 358
Katerina
  • 2,580
  • 1
  • 22
  • 25
  • 1
    Possible duplicate of [Generating a filled polygon inside a numpy array](http://stackoverflow.com/questions/37117878/generating-a-filled-polygon-inside-a-numpy-array) – ZdaR Jun 19 '16 at 08:21
  • @ZdaR I saw those question, but I don't know how to adopt it for multiple polygons – Katerina Jun 19 '16 at 08:24
  • Try to read the code and understand it's steps, Once you can do it for one, knowing what it is actually doing, then you can simply extend it to any number of polygons – ZdaR Jun 19 '16 at 08:26
  • Thanks, I already tried and I understand every step, but I cannot broadcast those function. And if I use for loops it will not be better then opencv solution. – Katerina Jun 19 '16 at 08:29
  • 1
    Here's an alternative idea : Draw lines between the points for each polygon with `cv2.line`. This would give us contour-ed image. So, finally, flood-fill that image starting from the top left corner, which would give us an inveres-ed version of your desired image, so just inverse as the last step. All of this is based on the assumption that `cv2.line` is faster than `cv2.fillConvexPoly`, which I am not sure is true. But, worth a shot I guess! Edit : I am not sure if drawling straight lines would maintain the convexity as done with `cv2.fillConvexPoly`, so it might not be correct. – Divakar Jun 19 '16 at 08:38
  • .. Continuing from my previous comment : For each polygon, if you connect each point to each of the other points that might maintain the convexity, so that might work! – Divakar Jun 19 '16 at 08:46
  • @Divakar Thank you, I will check if its faster, but I not sure as well) – Katerina Jun 19 '16 at 08:48
  • How many polygons do you have? Is it really such a problem to explicitly loop through the number of polygons? – gerrit Jun 20 '16 at 14:31

0 Answers0