# Intersection of centroid and line/rectangle

I'm currently making a traffic count system using opencv and python and what I exactly intend to do is that,to increment the counter as soon as the centroid of the blob passes or crosses a line or a small rectangle. My question is how to do this as I don't know how to implement cv2.lines or cv2.rectangle in this. Please see this video and if anybody could tell how exactly the intersection or counting is working in this video: https://www.youtube.com/watch?v=z1Cvn...

edit retag close merge delete

Sort by » oldest newest most voted Write the line as y=m*x+b, put in the x of the centroid, and if it changes from above the line to below, or vice-versa, then it has crossed the line.

A rectangle is to avoid noise. If you aren't quite sure of the true center of the blob, you only increment your counter when a blob goes from below the first to above the second, and vice-versa.

EDIT:

Point2f prevCenter;
Point2f blobCenter;
bool crossTop = false;
bool crossBottom = false;

int topLine = 100;
int bottomLine = 90;

if (!crossBottom &&
((prevCenter.y < bottomLine && blobCenter.y >= bottomLine)
|| (prevCenter.y >= bottomLine && blobCenter.y < bottomLine)))
{
crossBottom = true;
if (crossTop)
{
counter++;
}
}

if (!crossTop &&
((prevCenter.y < topLine && blobCenter.y >= topLine)
|| (prevCenter.y >= topLine && blobCenter.y < topLine)))
{
crossTop = true;
if (crossBottom)
{
counter++;
}
}

more

Thanks so much man! Umm, so i'll have to use two lines you're saying ? Sorry, i'm a bit confused.

The rectangle is two lines. You use that if your position is noisy. If your centroid path is smooth and it never goes backwards, then you'll be fine with one line.

Yes, mine is a bit noisy and the centroid does go back. So, i'm supposed to make two line equations and then put centroid x value into these two equations and check?

That would be best. Let's assume blobs are only going up and down, and your lines are horizontal.

I'm editing the answer with some basic code. If your lines are diagonal, replace the constants with the equation for the line.

Official site

GitHub

Wiki

Documentation