You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

568 lines
19 KiB

#include "blobDetector.h"
//http://www.keithlantz.net/2011/04/detecting-blobs-with-cvblobslib-and-tracking-blob-events-across-frames/
//http://opencv.willowgarage.com/wiki/cvBlobsLib
// filter parameters
static const int FKERNELSIZE = 7; //7// for gaussian blur
static const float FSTDDEV = 1.5;
static const int FBLOCKSIZE = 51; //47// for adaptive threshold
static const int FC = -5; //-5
blobDetector::blobDetector() :basicVideoAnalyzer(){
m_nMinArea = TMINAREA;
m_nMaxRadius = TMAXRADIUS;
type = VA_BLOB_DETECT;
m_vBlobs = NULL;
m_oFilter = new filterImage( FKERNELSIZE, FSTDDEV, FBLOCKSIZE, FC );
m_pIplThr = NULL;
m_pIplOrig = NULL;
m_pIplWork = NULL;
m_bPIP = true;
m_bUsePolygones = false;
m_bShowPolygones = false;
m_bShowRectangles = false;
m_bShowCentres = false;
m_nPrepMethod = 1;
m_bReduceSize = false;
memset(&m_aSegments, 0, V_SEGMENT_SIZE*H_SEGMENT_SIZE);
m_nCursorX = m_nCursorY = m_nStepX = m_nStepY = 0;
m_bCursorIsSet = false;
m_pPTZ = NULL;
m_nCamControllCurrent = 0;
};
blobDetector::blobDetector(float min_area, float max_radius) :basicVideoAnalyzer(){
m_nMinArea = min_area;
m_nMaxRadius = max_radius;
type = VA_BLOB_DETECT;
m_vBlobs = NULL;
m_oFilter = new filterImage( FKERNELSIZE, FSTDDEV, FBLOCKSIZE, FC );
m_pIplThr = NULL;
m_pIplOrig = NULL;
m_pIplWork = NULL;
m_bPIP = true;
m_bUsePolygones = false;
m_bShowPolygones = false;
m_bShowRectangles = false;
m_bShowCentres = false;
m_nPrepMethod = 1;
m_bReduceSize = false;
memset(&m_aSegments, 0, V_SEGMENT_SIZE*H_SEGMENT_SIZE);
m_nCursorX = m_nCursorY = m_nStepX = m_nStepY = 0;
m_bCursorIsSet = false;
m_pPTZ = NULL;
m_nCamControllCurrent = 0;
};
blobDetector::~blobDetector(){
if( m_vBlobs != NULL ) delete( m_vBlobs );
if( m_pIplThr != NULL ) delete( m_pIplThr );
if( m_pIplOrig != NULL ) delete( m_pIplOrig );
if( m_pIplWork != NULL ) delete( m_pIplWork );
delete( m_oFilter );
};
bool blobDetector::attachPTZ(basicCameraPTZ *cam){
if (cam == NULL) return false;
m_pPTZ = cam;
return true;
};
inline bool intersectBox(Rect A, Rect B){
bool intersectX = false;
bool intersectY = false;
if (A.x > B.x){
intersectX = B.x + B.width >= A.x;
} else {
intersectX = A.x + A.width >= B.x;
};
if (!intersectX) return false;
if (A.y > B.y){
intersectY = B.y + B.height >= A.y;
} else {
intersectY = A.y + A.height >= B.y;
};
if (!intersectY) return false;
return true;
};
inline void increaseBy(Rect &A, Rect &B){
int tAX, tAY, tBX, tBY;
tAX = A.x + A.width;
tAY = A.y + A.height;
tBX = B.x + B.width;
tBY = B.y + B.height;
A.x = (A.x > B.x) ? B.x : A.x;
A.y = (A.y > B.y) ? B.y : A.y;
A.width = (tAX > tBX) ? tAX - A.x : tBX - A.x;
A.height = (tAY > tBY) ? tAY - A.y : tBY - A.y;
};
bool blobDetector::m_fImageAnalyzer(Mat &Picture){
CBlobResult blob_result;
float x, y;
CvRect tRect;
cBlob temp;
if( Picture.empty() ) return false;
// Prepare Frame to deal with
if ( m_nPrepMethod ){
if (m_bReduceSize){
Mat tMat;
resize(Picture, tMat, Size(Picture.cols >> 1, Picture.rows >> 1), 0.0, 0.0, INTER_AREA);
m_oFilter->filter(tMat);
}else {
m_oFilter->filter(Picture);
};
// convert our OpenCV matrix object to one of type IplImage
if (m_pIplWork != NULL) {
delete(m_pIplWork);
};
m_pIplWork = new IplImage(m_oFilter->thresholdFrame());
} else {
Mat tMat;
if (m_bReduceSize){
resize(Picture, tMat, Size(Picture.cols >> 1, Picture.rows >> 1), 0.0, 0.0, INTER_AREA);
cvtColor(tMat, tMat, CV_RGB2GRAY);
}else{
cvtColor(Picture, tMat, CV_RGB2GRAY);
};
Mat tDelta;
//GaussianBlur(tMat, tMat, Size(7, 7), 0);
//medianBlur(tMat, tMat, 7);
//buildPyramid(tMat, tDelta, 255, BORDER_DEFAULT);
//blur(tMat, tDelta, Size(11,11) );
//blur(InputArray src, OutputArray dst, Size ksize, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT)
//adaptiveBilateralFilter(InputArray src, OutputArray dst, Size ksize, double sigmaSpace, double maxSigmaColor = 20.0, Point anchor = Point(-1, -1), int borderType = BORDER_DEFAULT)
//bilateralFilter(InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT)
//boxFilter(InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT)
//buildPyramid(InputArray src, OutputArrayOfArrays dst, int maxlevel, int borderType=BORDER_DEFAULT )
//GaussianBlur(InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY=0, int borderType=BORDER_DEFAULT )
//medianBlur(InputArray src, OutputArray dst, int ksize)
//Laplacian(InputArray src, OutputArray dst, int ddepth, int ksize=1, double scale=1, double delta=0, int borderType=BORDER_DEFAULT )
equalizeHist(tMat, tMat);
blur(tMat, tMat, Size(11, 11));
adaptiveThreshold(tMat, tMat, 255, cv::ADAPTIVE_THRESH_MEAN_C, cv::THRESH_BINARY, 47, -7 );
/// Detect edges using canny
//Canny(tMat, tMat, 100, 200, 3);
if (m_oMat.empty()){
tMat.copyTo(m_oMat);
return false;
};
tMat.copyTo(m_oMat);
//absdiff(m_oMat, tMat, tThresh);// tDelta);
tMat.copyTo(tThresh);
//threshold(tDelta, tThresh, 50, 255, THRESH_BINARY);
// convert our OpenCV matrix object to one of type IplImage
if (m_pIplWork != NULL) {
delete(m_pIplWork);
};
m_pIplWork = new IplImage(tThresh);
};
if(m_bCursorIsSet == false){
m_nCursorX = Picture.cols / 2;
m_nCursorY = Picture.rows / 2;
m_bCursorIsSet = true;
};
/*
// Set up the detector with default parameters.
SimpleBlobDetector detector;
// Detect blobs.
std::vector<KeyPoint> keypoints;
detector.detect(Picture, keypoints);
// Draw detected blobs as red circles.
// DrawMatchesFlags::DRAW_RICH_KEYPOINTS flag ensures the size of the circle corresponds to the size of blob
//Mat im_with_keypoints;
if (keypoints.size()> 0) drawKeypoints(tThresh, keypoints, tThresh, Scalar(0, 0, 255), DrawMatchesFlags::DRAW_RICH_KEYPOINTS);
*/
// cvblobslib blob extraction
blob_result = CBlobResult( m_pIplWork, NULL, 0 );//, false );
// filter blobs with area less than min_area units
blob_result.Filter( blob_result, B_EXCLUDE, CBlobGetArea(), B_LESS, m_nMinArea );
// clear the blobs from two frames ago
blobs_previous.clear();
// before we populate the blobs vector with the current frame, we need to store the live blobs in blobs_previous
for (int i = 0; i < blobs.size(); i++)
//if( blobs[i].event != BLOB_STEADY )
blobs_previous.push_back(blobs[i]);
// populate the blobs vector with the current frame
blobs.clear();
for (int i = 1; i < blob_result.GetNumBlobs(); i++){
temp.ConvexHull.clear();
current_blob = blob_result.GetBlob(i);
if (m_bUsePolygones){
CBlobContour *tContour;
tContour = current_blob.GetExternalContour();
if (tContour != NULL){
//if (!tContour->IsEmpty()){
if (!tContour->IsEmpty()){
for (int dex = 0; dex < tContour->GetContourPoints()->total; dex++){
point2D p2D;
CvPoint* p = (CvPoint*)cvGetSeqElem(tContour->GetContourPoints(), dex);
p2D.x = p->x;
p2D.y = p->y;
temp.ConvexHull.push_back(p2D);
};
};
};
};
x = XCenter(current_blob);
y = YCenter(current_blob);
tRect = current_blob.GetBoundingBox();
if (m_bReduceSize){
temp.location.x = temp.origin.x = x * 2.f;
temp.location.y = temp.origin.y = y * 2.f;
tRect.height = tRect.height << 1;
tRect.width = tRect.width << 1;
tRect.x = tRect.x << 1;
tRect.y = tRect.y << 1;
}else{
temp.location.x = temp.origin.x = x;
temp.location.y = temp.origin.y = y;
tRect.height = tRect.height;
tRect.width = tRect.width;
tRect.x = tRect.x;
tRect.y = tRect.y;
};
//temp.ConvexHull = current_blob.GetConvexHull();
temp.box = tRect;
temp.area = current_blob.Area();
temp.event = BLOB_NEW;
temp.id = current_blob.GetID();
temp.color = Scalar(128, 128, 128);
temp.tracked = false;
temp.weight = 0;
blobs.push_back(temp);
};
// initialize previous blobs to untracked
for (int i = 0; i < blobs_previous.size(); i++) blobs_previous[i].tracked = false;
bool history = false;
memset(&m_aSegments, 0, V_SEGMENT_SIZE*H_SEGMENT_SIZE);
// main tracking loop -- O(n^2) -- simply looks for a blob in the previous frame within a specified radius
float dx, dy; int rrr;
m_fSegmentStepX = ((float)Picture.cols) / ((float)H_SEGMENT_SIZE);
m_fSegmentStepY = ((float)Picture.rows) / ((float)V_SEGMENT_SIZE);
for (int i = 0; i < blobs.size(); i++) {
for (int j = 0; j < blobs_previous.size(); j++) {
// Skip already connected
if (blobs_previous[j].tracked == true) continue;
dx = blobs[i].location.x - blobs_previous[j].location.x;
dy = blobs[i].location.y - blobs_previous[j].location.y;
rrr = (int)sqrt(pow(dx, 2.0f) + pow(dy, 2.0f));
if ( rrr < m_nMaxRadius ){
blobs[i].event = BLOB_STEADY;
blobs[i].color = Scalar(0, 255, 0 );
blobs[i].id = blobs_previous[j].id;
blobs[i].weight = blobs_previous[j].weight+1;
blobs[i].origin.x = history ? blobs_previous[j].origin.x : blobs_previous[j].location.x;
blobs[i].origin.y = history ? blobs_previous[j].origin.y : blobs_previous[j].location.y;
blobs_previous[j].tracked = true;
// Done with that point
break;
};
};
// If did not found old point
if (blobs[i].event == BLOB_NEW){
blobs[i].origin.x = blobs[i].location.x;
blobs[i].origin.y = blobs[i].location.y;
} else {
dx = blobs[i].origin.x - blobs[i].location.x;
dy = blobs[i].origin.y - blobs[i].location.y;
rrr = (int)sqrt(pow(dx, 2.0f) + pow(dy, 2.0f));
if( rrr > 10 ){
blobs[i].event = BLOB_MOVE;
blobs[i].color = Scalar(0, 0, 255);
// blobs[i].dir = atanf(dx / dy);
};// else blobs[i].dir = 0.f;
};
//if (blobs[i].event == BLOB_MOVE ) m_aSegments[(U8)(blobs[i].location.y / m_fSegmentStepY)][(U8)(blobs[i].location.x / m_fSegmentStepX)]++;
// Rect Intersect bool intersects = ((A & B).area() > 0);
};
for (int i = 0; i < blobs.size() / 2; i++) {
if (blobs[i].event == BLOB_MOVE){
for (int j = i + 1; j < blobs.size(); j++){
if (blobs[j].event == BLOB_MOVE){
if (intersectBox(blobs[i].box, blobs[j].box)){
increaseBy(blobs[i].box, blobs[j].box);
blobs[j].event = BLOB_NEW;
};
};
};
};
};
// add any blobs from the previous frame that weren't tracked as having been removed
//for (int i = 0; i < blobs_previous.size(); i++) {
// if (!blobs_previous[i].tracked) {
// blobs_previous[i].event = BLOB_NEW;
// blobs.push_back(blobs_previous[i]);
// };
//};
/*
if( m_pIplOrig != NULL ) {
if( m_pIplThr== NULL ){
m_pIplThr = cvCreateImage( cvGetSize( m_pIplOrig ), IPL_DEPTH_8U, 1 );
};
if( m_pIplWork == NULL ){
m_pIplWork = new IplImage( tMat );
} else {
delete( m_pIplWork );
m_pIplWork = new IplImage( tMat );
};
} else {
m_pIplOrig = new IplImage( tMat );
return false;
};
// threshold input image
cvThreshold( m_pIplOrig, m_pIplThr, m_nParam1, 255, CV_THRESH_BINARY );
// get blobs and filter them using its area
// find blobs in image
//if( m_vBlobs != NULL ) delete( m_vBlobs );
m_vBlobs = new CBlobResult( m_pIplThr, NULL, 255 );
if( m_vBlobs!= NULL ){
m_vBlobs->Filter( *m_vBlobs, B_EXCLUDE, CBlobGetArea(), B_LESS, m_nParam2 );
return true;
}; */
return true;
};
vector<cBlob>& blobDetector::getBlobs() {
return blobs;
};
bool blobDetector::lookupMaxActiveSegment(U8 &x, U8 &y){
int MaxVal = 0;
x = y = 0;
for (U8 i = 0; i < V_SEGMENT_SIZE; i++)
for (U8 j = 0; j < H_SEGMENT_SIZE; j++){
if (m_aSegments[i][j] > MaxVal){
x = j;
y = i;
MaxVal = m_aSegments[i][j];
};
};
if (MaxVal == 0)return false;
return true;
};
void blobDetector::markup(Mat &Picture){
char Buffer[200];
sprintf( Buffer, "Blobs: %d", blobs.size() );
rectangle( Picture, Point( Picture.cols-220, 5 ), Point( Picture.cols-120, 15 ), Scalar( 0, 255, 255 ), CV_FILLED );
putText( Picture, Buffer, Point( Picture.cols-215, 13 ), FONT_HERSHEY_SIMPLEX, 0.3, Scalar( 255, 0, 0 ), 1 );
if (m_bShowPolygones || m_bShowRectangles || m_bShowCentres){
for (int i = 0; i < blobs.size(); i++) {
if (blobs[i].event == BLOB_MOVE){
//rectangle(Picture, blobs[i].box, blobs[i].color, 2);// CV_FILLED);
//sprintf(Buffer, "%d:%d [%.2f]", blobs[i].id, blobs[i].weight, blobs[i].area );
//putText(Picture, Buffer, Point(blobs[i].box.x, blobs[i].box.y), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 0), 1);
//circle(Picture, Point(blobs[i].location.x, blobs[i].location.y), 5, blobs[i].color, 2, 8);
//if (m_bShowRectangles )
rectangle(Picture, blobs[i].box, blobs[i].color, 2);
if (m_bShowPolygones){
for (int j = 0; j < blobs[i].ConvexHull.size() - 1; j++) {
Point p1, p2;
//CV_READ_SEQ_ELEM(pt[0], reader);
//CV_READ_SEQ_ELEM(pt[1], reader);
p1.x = blobs[i].ConvexHull.at(j).x;
p1.y = blobs[i].ConvexHull.at(j).y;
p2.x = blobs[i].ConvexHull.at(j + 1).x;
p2.y = blobs[i].ConvexHull.at(j + 1).y;
//cvLine(&Picture, p1, p2, CV_RGB(255, 0, 0));
line(Picture, p1, p2, Scalar(0, 255, 255));
};
};
if (m_bShowCentres) circle(Picture, Point(blobs[i].origin.x, blobs[i].origin.y), 1, blobs[i].color, 1, 8);
//circle(Picture, Point(blobs[i].location.x, blobs[i].location.y), 15, Scalar(255, 255, 255), 2, 8);
} else {
if (m_bShowCentres) circle(Picture, Point(blobs[i].origin.x, blobs[i].origin.y), 1, blobs[i].color, 1, 8);
if (m_bShowPolygones){
for (int j = 0; j < blobs[i].ConvexHull.size() - 1; j++) {
Point p1, p2;
p1.x = blobs[i].ConvexHull.at(j).x;
p1.y = blobs[i].ConvexHull.at(j).y;
p2.x = blobs[i].ConvexHull.at(j + 1).x;
p2.y = blobs[i].ConvexHull.at(j + 1).y;
line(Picture, p1, p2, Scalar(0, 0, 255));
};
};
};
};
};
/*
U8 X, Y;
int x, y, w, h;
int mCamControllNew;
if (blobs.size() > 0){
if (lookupMaxActiveSegment(X, Y)){
mCamControllNew = 0;
x = (int)X*m_fSegmentStepX;
y = (int)Y*m_fSegmentStepY;
w = (int)m_fSegmentStepX;
h = (int)m_fSegmentStepY;
//sprintf(Buffer, "%d", m_aSegments[Y][X]);
//putText(Picture, Buffer,Point( x, y ), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255, 0, 255), 1);
rectangle(Picture, Rect(x, y, w, h), Scalar(255, 128, 0), 4);
if (X == 0){
m_nStepX = -(m_aSegments[Y][X] - blobs.size() / 9);
mCamControllNew &= ~3;
mCamControllNew |= 2;
} else if (X == 1){
m_nStepX = 0;
m_nCursorX = Picture.cols / 2;
mCamControllNew &= ~3;
} else if (X == 2){
m_nStepX = m_aSegments[Y][X] - blobs.size() / 9;
mCamControllNew &= ~3;
mCamControllNew |= 1;
};
if (Y == 0){
m_nStepY = -(m_aSegments[Y][X] - blobs.size() / 9);
mCamControllNew &= ~12;
mCamControllNew |= 8;
} else if (Y == 1 ){
m_nStepY = 0;
m_nCursorY = Picture.rows / 2;
mCamControllNew &= ~12;
} else if (Y == 2){
m_nStepY = m_aSegments[Y][X] - blobs.size() / 9;
mCamControllNew &= ~12;
mCamControllNew |= 4;
};
m_nCursorX += m_nStepX;
m_nCursorY += m_nStepY;
if( m_nCamControllCurrent ){
int HW, HH;
float s1, s2;
HW = Picture.cols / 2;
HH = Picture.rows / 2;
s1 = (float)((m_nCursorX < HW) ? (HW - m_nCursorX) : (m_nCursorX - HW)) / (float)HW;
s2 = (float)((m_nCursorY < HH) ? (HH - m_nCursorY) : (m_nCursorY - HH)) / (float)HH;
//m_pProtocol->setPTZSpeed(s1,s2,0.);
//if (m_pPTZ != NULL) m_pPTZ->setSpeed(s1);
}
if (m_nCursorX < 0)m_nCursorX = 0;
if (m_nCursorX > Picture.cols)m_nCursorX = Picture.cols;
if (m_nCursorY < 0)m_nCursorY = 0;
if (m_nCursorY > Picture.rows)m_nCursorY = Picture.rows;
if (m_nCamControllCurrent != mCamControllNew){
if (m_pPTZ != NULL){
switch (mCamControllNew){
case 0:
m_pPTZ->cmdEndManualTilt();
m_pPTZ->cmdEndManualPan();
break;
case 1:
m_pPTZ->cmdBeginPanRight();
break;
case 2:
m_pPTZ->cmdBeginPanLeft();
break;
case 4:
m_pPTZ->cmdBeginTiltDown();
break;
case 5:
//m_pProtocol->goDownRight();
m_pPTZ->cmdBeginPanRight();
m_pPTZ->cmdBeginTiltDown();
break;
case 6:
//m_pProtocol->goDownLeft();
m_pPTZ->cmdBeginPanLeft();
m_pPTZ->cmdBeginTiltDown();
break;
case 8:
m_pPTZ->cmdBeginTiltUp();
break;
case 9:
//m_pProtocol->goUpRight();
m_pPTZ->cmdBeginPanRight();
m_pPTZ->cmdBeginTiltUp();
break;
case 10:
//m_pProtocol->goUpLeft();
m_pPTZ->cmdBeginPanLeft();
m_pPTZ->cmdBeginTiltUp();
break;
};
};
m_nCamControllCurrent = mCamControllNew;
};
};
};
// Cursor
line(Picture, Point(m_nCursorX, 0), Point(m_nCursorX, Picture.rows), Scalar(255, 255, 0), 2);
line(Picture, Point(0, m_nCursorY), Point(Picture.cols, m_nCursorY), Scalar(255, 255, 0), 2);
//*/
// PIP
if (m_bPIP){
Mat resizedSrc;
Mat subView;
Mat convertedSrc;
/*
if (!m_oFilter->filterFrame().empty()){
resize(m_oFilter->filterFrame(), resizedSrc, Size(160, 120), 0.0, 0.0, INTER_AREA);
subView = Picture(Rect((Picture.cols - 510), 50 + 120, 160, 120));
cvtColor(resizedSrc, convertedSrc, CV_GRAY2BGR);
convertedSrc.copyTo(subView);
};
if (!m_oFilter->gaussianFrame().empty()){
resize(m_oFilter->gaussianFrame(), resizedSrc, Size(160, 120), 0.0, 0.0, INTER_AREA);
subView = Picture(Rect((Picture.cols - 340), 50 + 120, 160, 120));
cvtColor(resizedSrc, convertedSrc, CV_GRAY2BGR);
convertedSrc.copyTo(subView);
};*/
if (m_nPrepMethod){
if (!m_oFilter->thresholdFrame().empty()){
resize(m_oFilter->thresholdFrame(), resizedSrc, Size(160, 120), 0.0, 0.0, INTER_AREA);
subView = Picture(Rect((Picture.cols - 170), 50 + 120, 160, 120));
cvtColor(resizedSrc, convertedSrc, CV_GRAY2BGR);
convertedSrc.copyTo(subView);
};
} else {
if (!tThresh.empty()){
resize(tThresh, resizedSrc, Size(160, 120), 0.0, 0.0, INTER_AREA);
subView = Picture(Rect((Picture.cols - 170), 50 + 120, 160, 120));
cvtColor(resizedSrc, convertedSrc, CV_GRAY2BGR);
convertedSrc.copyTo(subView);
};
};
};
};