wb666greene / AI-Person-Detector

Python Ai "person detector" using Coral TPU or Movidius NCS/NCS2
17 stars 4 forks source link

point-in-polygon functionality? #2

Open ozett opened 4 years ago

ozett commented 4 years ago

i looked through the rtsp2mqtt code and again through your readme.md and found that piece with "point-in-poligon".

would you be so kind to show in little more detail how you implementet this check in the node-red function (code/cod-image?) and the use of the npm-package to test against points lying within the image? Why dont you do this in python per camera? (pyimagesarch has some code, i think)

greatly appreicate this, thankx toz

wb666greene commented 4 years ago

I do it in node-red instead of in the Python because changes won't require restarting the rtsp streams which can take typically 6-20 seconds per stream. Its also much more flexible.

Its just Javascript in the node-red function node:

`/ LorexAI "in alert region" filter. Install point-in-polygon with: cd ~/.node-red npm install point-in-polygon var inside = require('point-in-polygon'); // doesn't work in node-red. So must edit .node-red/settings.js and add: functionGlobalContext: { insidePolygon:require('point-in-polygon') } Requires a node-red restart when finished. /

var inside = global.get('insidePolygon'); msg.InAlertRegion=true; // default is to accept detection anywhere in image

// screen for LR box point in region var poly=[[]];

// polygon points picked from image using GIMP if(msg.filename.includes("Cam0")) poly=[ [0,0], [0,350], [1301,370], [1301,0] ]; else if(msg.filename.includes("Cam1")) poly=[ [0,0], [0,400], [1150,400], [1150,0] ]; else if(msg.filename.includes("Cam2")) poly=[ [15,60], [1195,20], [1195,190], [1100,190], [960,265], [15,265] ];

if(poly.length > 2) msg.InAlertRegion = inside([msg.endX, msg.endY], poly); // returns false if point not inside polygon ` There is no reason you can't do it in the Python code, but I find doing it in node-red is much more flexible.

Here is a Python "point in polygoc" function I found on the web and have used in the Python code before I decided doing it in node-red was better for my needs:

`# determine if a point is inside a given polygon or not

code from: http://www.ariel.com.au/a/python-point-int-poly.html

algorthim: http://paulbourke.net/geometry/polygonmesh/

#

Polygon is a list of (x,y) pairs.

def point_inside_polygon(x,y,poly):

n = len(poly)
inside =False

p1x,p1y = poly[0]
for i in range(n+1):
    p2x,p2y = poly[i % n]
    if y > min(p1y,p2y):
        if y <= max(p1y,p2y):
            if x <= max(p1x,p2x):
                if p1y != p2y:
                    xinters = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                if p1x == p2x or x <= xinters:
                    inside = not inside
    p1x,p1y = p2x,p2y

return inside

`

npm installs "extra" Javascript modules to your system, you need to modify .node-red/settings.js as shown in the comment to make the added modue active inside of node-red.