I searched a lot and cant find any practical answer to my question. I have a polygon. For example:
[(86, 52), (85, 52), (81, 53), (80, 52), (79, 48), (81
You can use a numpy matrix like a binary image, which can be used with Opencv for example or other image processing libs, Solution 1 So a matrix which size is L x H where
L=max(x) - min (x)
H=max(y) - min (y)
As entry we have your list of tuple(x,y) you gave above which name is poly for example :
import numpy as np
matrix =np.zeros((L,H),dtype=np.int32) # you can use np.uint8 if unsigned x ,y
So we have now a matrix of Size L x H filled with 0, we put now 1 at polygon points positions
I think you can simple do that
matrix[poly]=1 # which will put 1 at each (x,y) of the list **poly**
we interpret this as a binary (black/white) image which have a contour drawn on it Assume we want to detect this new contour
import cv2 # opencv import
ContoursListe,hierarchy = cv2.findContours(self.thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)
poly2=ContoursListe[0] # we take the first only contour
Note : poly2 is containing a list of points of your polygon and all points forming it, i mean all points of each vertices of your polygon which is what you need can find useful !! you can use cv2.CHAIN_APPROX_SIMPLE parameter to get poly2 containing only end points of the polygon lines which is lighter and which was our input :) important :the type of poly2 is numpy array ,its shape is (n,1,2) and not (n,2)
Now we draw this contour on this image(matrix) and will fill it too :)
cv2.drawContours(matrix,[poly2],-1,(1),thickness=-1)
thickness=-1
now we have a matrix where there is 1 on each points forming and filling the polygon , "thickness=-1" has forced to fill this contour, you can put set thickness = 1 to get only the borders if you want to translate, you can do it by adding parameter offset(xtran,ytrans)
to get the indices of all theses points simply call
list_of_points_indices=numpy.nonzero(matrix)
Solution 2
Which is smarter is to directly transform your list of points (poly) to a contour format (poly2) and draw it on the matrix
poly2=poly.reshape(-1,1,2).astype(np.int32)
and draw it on the Matrix matrix
matrix =np.zeros((L,H),dtype=np.int32)
cv2.drawContours(matrix,[poly2],-1,(1),thickness=-1)
And get the list of this points with :
list_of_points_indices=numpy.nonzero(matrix)
Play with thickness to fill or not the polygon , see solution 1 for more details.