CBM_model.cpp 22.5 KB
Newer Older
wanghailong's avatar
wanghailong committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
#include "CBM_model.h"
#include <iostream>
#include <omp.h>
#include "DetectAnomaly.h"

using namespace std;
using namespace cv;

CBM_model::CBM_model(myImage * input, int set_MOG_LearnFrame, int set_min_area, int set_buffer_len, float set_resize, myImage * mask)
{
	frame_count = 0;
	sampling_idx = 0;
	FG_count = 0;
	RESIZE_RATE = set_resize;

	MOG_LEARN_FRAMES = set_MOG_LearnFrame;
	MIN_AREA = set_min_area;
	TEMPORAL_RULE = set_buffer_len;

	new_width = (int)(input->width) * RESIZE_RATE;
	new_height = (int)(input->height) * RESIZE_RATE;

	Initialize();

	// Select parameters for Gaussian model.
	_myGMM = new myGMM(0.0001);//0.0001
	_myGMM2 = new myGMM(0.002);

	maskROI = mask;


	// const char* model_filename = "DPM_person.xml";
    // // detector = cvLoadLatentSvmDetector(model_filename);
	// //detector = cv::ml::StatModel::load<cv::ml::SVM>("DPM_person.xml");
    // if (detector == nullptr)
    // {
    //     printf( "Unable to load the model\n"
    //             "Pass it as the second parameter: latentsvmdetect <path to cat.jpg> <path to cat.xml>\n" );
    //     //system("pause");
	// 	//return;
    // }	


	// hog = HOGDescriptor(cv::Size(Win_width,Win_height),cv::Size(Block_size,Block_size),cv::Size(Block_stride,Block_stride),cv::Size(Cell_size,Cell_size),Bin_num);
	// hog.setSVMDetector(HOGDescriptor::getDefaultPeopleDetector());
}

CBM_model::~CBM_model()
wanghailong's avatar
wanghailong committed
49
{	
wanghailong's avatar
wanghailong committed
50 51 52 53
	Uninitialize();
}
void CBM_model::Initialize()
{	
54 55 56 57
	// _writer6.open("long.avi",cv::VideoWriter::fourcc('X','V','I','D'),30,cv::Size(new_width,new_height),0);
	// _writer7.open("short.avi",cv::VideoWriter::fourcc('X','V','I','D'),30,cv::Size(new_width,new_height),0);
	// _writer8.open("static.avi",cv::VideoWriter::fourcc('X','V','I','D'),30,cv::Size(new_width,new_height),1);
	// _writer10.open("DPM.avi",cv::VideoWriter::fourcc('X','V','I','D'),30,cv::Size(new_width,new_height),1);
wanghailong's avatar
wanghailong committed
58 59


60 61 62
	// mog_fg = cv::Mat::zeros(cv::Size(new_width, new_height), CV_8UC1);
	// mog_fg2 = cv::Mat::zeros(cv::Size(new_width, new_height), CV_8UC1);
	// imgStatic = cv::Mat::zeros(cv::Size(new_width, new_height), CV_8UC3);
wanghailong's avatar
wanghailong committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102

	my_mog_fg = myCreateImage( new_width, new_height, 1);
	my_mog_fg2 = myCreateImage( new_width, new_height, 1);
	my_imgCandiStatic = myCreateImage( new_width, new_height, 3);
	my_imgStatic = myCreateImage( new_width, new_height, 3);

	imageFSM = (pixelFSM **)malloc((int)new_width*sizeof( pixelFSM *));

	// cvZero(mog_fg);
	// cvZero(mog_fg2);
	// cvZero(imgStatic);

	input_temp = myCreateImage(new_width, new_height, 1);		

	for (int i = 0; i < new_width; i++){
		imageFSM[i] = (pixelFSM *)malloc((int)new_height*sizeof(pixelFSM));
	}

	Previous_FG = (bool ***)malloc(TEMPORAL_RULE*sizeof(bool **));
	for (int i = 0; i < TEMPORAL_RULE; i++){
		Previous_FG[i] = (bool **)malloc((int)new_width*sizeof(bool *));
	}
	for (int i = 0; i < TEMPORAL_RULE; i++){
		for (int j = 0; j < new_width; j++){
			Previous_FG[i][j] = (bool *)malloc((int)new_height*sizeof(bool));
		}
	}


	//printf("..\n");
	_Previous_Img = (myImage **)malloc(TEMPORAL_RULE*sizeof(myImage *));
	for ( int i = 0; i < TEMPORAL_RULE; i++){
		_Previous_Img[i] = myCreateImage( new_width, new_height, 3);			
	}
	//printf("....\n");

	staticFG_pixel_num_now = -1;
	staticFG_pixel_num_pre = -2;
	staticFG_pixel_num_pre2 = -3;

wanghailong's avatar
wanghailong committed
103
	//dpm_gray = myCreateImage(new_width, new_height, 1);
wanghailong's avatar
wanghailong committed
104 105 106 107 108
	//std::cout << " chushihua ok";
}
void CBM_model::Uninitialize()
{
#ifdef DEBUG
109 110 111 112
	// _writer6.release();
	// _writer7.release();
	// _writer8.release();
	// _writer10.release();
wanghailong's avatar
wanghailong committed
113
#endif
wanghailong's avatar
wanghailong committed
114 115 116

	delete _myGMM;
	delete _myGMM2;
wanghailong's avatar
wanghailong committed
117 118 119 120 121 122 123 124 125 126 127
	
	// cvReleaseImage(&mog_fg);
	// cvReleaseImage(&mog_fg2);
	// cvReleaseImage(&imgStatic);

	my_mog_fg->myReleaseImage();
	my_mog_fg2->myReleaseImage();
	my_imgCandiStatic->myReleaseImage();
	my_imgStatic->myReleaseImage();
	input_temp->myReleaseImage();

wanghailong's avatar
wanghailong committed
128 129 130 131 132 133
	delete my_mog_fg;
	delete my_mog_fg2;
	delete my_imgCandiStatic;
	delete my_imgStatic;
	delete input_temp;

wanghailong's avatar
wanghailong committed
134 135
	for (int i = 0; i < TEMPORAL_RULE; i++){
		_Previous_Img[i]->myReleaseImage();
wanghailong's avatar
wanghailong committed
136 137
		delete _Previous_Img[i];
		_Previous_Img[i] = nullptr;
wanghailong's avatar
wanghailong committed
138
	}
wanghailong's avatar
wanghailong committed
139 140
	free(_Previous_Img);
	_Previous_Img = nullptr;
wanghailong's avatar
wanghailong committed
141

wanghailong's avatar
wanghailong committed
142 143 144 145
	for (int i = 0; i < new_width; i++){
		free(imageFSM[i]);
		imageFSM[i] = nullptr;
	}
wanghailong's avatar
wanghailong committed
146
	free(imageFSM);
wanghailong's avatar
wanghailong committed
147 148 149 150 151 152 153 154 155 156 157
	imageFSM = nullptr;

	for (int i = 0; i < TEMPORAL_RULE; i++){
		for (int j = 0; j < new_width; j++){
			free(Previous_FG[i][j]);
			Previous_FG[i][j] = nullptr;
		}
	}
	for (int i = 0; i < TEMPORAL_RULE; i++){
		free(Previous_FG[i]);
	}
wanghailong's avatar
wanghailong committed
158
	free(Previous_FG);
wanghailong's avatar
wanghailong committed
159 160 161 162 163 164 165 166
	Previous_FG = nullptr;


	// free(*imageFSM);
	// free(imageFSM);
	// free(**Previous_FG);
	// free(*Previous_FG);
	// free(Previous_FG);
wanghailong's avatar
wanghailong committed
167 168 169 170 171
	//cout<<"CBM_model Released!"<<endl;
}

void CBM_model::System_Reset()
{
wanghailong's avatar
wanghailong committed
172
#pragma omp parallel for num_threads(12)
wanghailong's avatar
wanghailong committed
173 174 175 176 177 178 179 180 181 182 183
	for (int i = 0; i < new_width; i++){
		for (int j = 0; j < new_height; j++){
			imageFSM[i][j].state_now = 0;
			imageFSM[i][j].staticFG_stable = false;
			imageFSM[i][j].staticFG_candidate = false;
			imageFSM[i][j].static_count = 0;
		}
	}
	static_object_result.clear();
}

wanghailong's avatar
wanghailong committed
184
bool CBM_model::Build_model(myImage *img){
wanghailong's avatar
wanghailong committed
185 186 187 188
 	myResize(img, _Previous_Img[FG_count]);

	if( frame_count < MOG_LEARN_FRAMES){
#ifdef DEBUG
wanghailong's avatar
wanghailong committed
189
		printf("update mog %d\n",MOG_LEARN_FRAMES-frame_count);
wanghailong's avatar
wanghailong committed
190 191 192 193 194 195 196 197 198 199 200
#endif

		if (frame_count==0){
			_myGMM->initial(_Previous_Img[FG_count]);
			_myGMM2->initial(_Previous_Img[FG_count]);
		}
		_myGMM->process(_Previous_Img[FG_count],my_mog_fg);
		_myGMM2->process(_Previous_Img[FG_count],my_mog_fg2);

		frame_count++;

201 202 203
		// _writer6.write(mog_fg);
		// _writer7.write(mog_fg2);
		// _writer8.write(imgStatic);
wanghailong's avatar
wanghailong committed
204 205 206
		return false;
	}
	else{
wanghailong's avatar
wanghailong committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235
		//std::cout << "build model succeed\n";
		return true;
	}	
}

bool CBM_model::Motion_Detection(myImage *img)
{
 	myResize(img, _Previous_Img[FG_count]);

// 	if( frame_count < MOG_LEARN_FRAMES){
// #ifdef DEBUG
// 		printf("update mog %d\n",MOG_LEARN_FRAMES-frame_count);
// #endif

// 		if (frame_count==0){
// 			_myGMM->initial(_Previous_Img[FG_count]);
// 			_myGMM2->initial(_Previous_Img[FG_count]);
// 		}
// 		_myGMM->process(_Previous_Img[FG_count],my_mog_fg);
// 		_myGMM2->process(_Previous_Img[FG_count],my_mog_fg2);

// 		frame_count++;

// 		// _writer6.write(mog_fg);
// 		// _writer7.write(mog_fg2);
// 		// _writer8.write(imgStatic);
// 		return false;
// 	}
// 	else{
wanghailong's avatar
wanghailong committed
236 237 238 239 240 241 242 243
		//printf("start detect\n");
		//***MOG model***//
		_myGMM->process(_Previous_Img[FG_count],input_temp);
		myImageAND(input_temp,maskROI,my_mog_fg);

		_myGMM2->process(_Previous_Img[FG_count],input_temp);
		myImageAND(input_temp,maskROI,my_mog_fg2);

244 245
		myDiladeitself( my_mog_fg, 3);
		myDiladeitself( my_mog_fg2, 3);
wanghailong's avatar
wanghailong committed
246 247 248 249 250 251 252 253 254 255 256 257 258 259

		if (check_foreground2(my_mog_fg)>(my_mog_fg->width*my_mog_fg->height*0.30)){//if motion detection cannot work well
 			_myGMM->ChangeLearningRate(0.02);//speed up long-term model's learning rate to adapt the lighting changes.
		}
		else{
			_myGMM->ChangeLearningRate(0.0001);//defult long-term model learning rate
		}
		myFSM( my_mog_fg2, my_mog_fg, imageFSM, Previous_FG);	
		myConvertFSM2Img( imageFSM, my_imgCandiStatic, my_imgStatic);

		staticFG_pixel_num_pre2 = staticFG_pixel_num_pre;
		staticFG_pixel_num_pre = staticFG_pixel_num_now;
        staticFG_pixel_num_now = check_foreground2(my_imgStatic);

260 261 262
 		// myImage_2_opencv(my_imgStatic,imgStatic);
		// myImage_2_opencv(my_mog_fg,mog_fg);
		// myImage_2_opencv(my_mog_fg2,mog_fg2);
wanghailong's avatar
wanghailong committed
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
		// cv::imwrite("static_obj.jpg", imgStatic);
 		// cv::imwrite("Long-term.jpg", mog_fg);
 		// cv::imwrite("Short-term.jpg", mog_fg2);
		//  该处出现停顿
		//cv::waitKey(10);
		bool static_object_detected = false;
		//std::cout << " pre :" << staticFG_pixel_num_pre << " now " << staticFG_pixel_num_now << " pre2 " << staticFG_pixel_num_pre2 <<"\n"
			      //<< " number "<<staticFG_pixel_num_now<<std::endl;
		if((staticFG_pixel_num_now==staticFG_pixel_num_pre)&&(staticFG_pixel_num_pre==staticFG_pixel_num_pre2)&&(staticFG_pixel_num_now>0))
		{
			static_object_detected = myClustering2( my_imgStatic, 1);
			//std::cout << " static_object_detected : " << static_object_detected << std::endl;
		}


278 279 280
		// _writer6.write(mog_fg);
		// _writer7.write(mog_fg2);
		// _writer8.write(imgStatic);
wanghailong's avatar
wanghailong committed
281 282 283 284 285

		FG_count = FG_count + 1;
		FG_count = FG_count%TEMPORAL_RULE;
		
		return static_object_detected;
wanghailong's avatar
wanghailong committed
286
	//}
wanghailong's avatar
wanghailong committed
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
}


bool CBM_model::myClustering2( myImage *img, int option)
{
	int area_threshold = 0;
	myImage * temp;
	temp = myCreateImage(new_width, new_height, 1);
	if (img->depth==3)//static foreground object
	{
		myRGB2Gray(img, temp);
		area_threshold = MIN_AREA/2;//0;
	}
	else if (img->depth==1)//foreground detection
	{
		myImageCopy( img, temp);
		area_threshold = MIN_AREA;
	}
	
	int found_objnum = 0;

	found_objnum = GetLabeling2( temp, area_threshold, option);
	//printf("myClustering: found_objnum=%d\n",found_objnum);

	temp->myReleaseImage();
	delete(temp);

	if (found_objnum > 0){
		return true;
	}
	else{
		return false;
	}
}

/************************************************************************/
/*                                                                      
GetLabeling : input a binary frame, bounding the connected component.
Ignore the connected component when :  case1.  It's pixel is more than a areaThreshold.
                                       case2.  The bounding rectangle is too thin or fat.  */
/************************************************************************/
int CBM_model::GetLabeling2( myImage *pImg1, int areaThreshold, int option) 
{   
    int	found_objnum = 0; 
	if ( option == 0)
		detected_result.clear();//clear the vector
	if ( option == 1)
		static_object_result.clear();//clear the vector

    //find object's conturs of binary frame 
    unsigned int *out = (unsigned int *)malloc(sizeof(*out)* pImg1->width*pImg1->height);

	for (int i = 0; i < pImg1->width*pImg1->height; i++){
		out[i] = pImg1->pixelData[i];
	}

    ConnectedComponents cc(30);
    cc.connected(pImg1->pixelData, out, pImg1->width, pImg1->height,
					std::equal_to<unsigned char>(),
					constant<bool,true>());

	// myImage * temp;
	// temp = myCreateImage(pImg1->width, pImg1->height, 3);
  	// cv::Mat ttt = cv::Mat(cv::Size(pImg1->width, pImg1->height), CV_8UC3);
	// for (int i = 0; i < pImg1->width*pImg1->height; i++){
	// 	temp->pixelData[i] = out[i]*20;
	// 	temp->pixelData[i + pImg1->width*pImg1->height] = out[i]*20;
	// 	temp->pixelData[i + pImg1->width*pImg1->height*2] = out[i]*20;
	// }

wanghailong's avatar
wanghailong committed
357
	bool constant_template[2474]={false}; //change 256->448
wanghailong's avatar
wanghailong committed
358 359 360
	vector<int> color_labels;
	color_labels.clear();
	for (int i = 0; i < pImg1->width*pImg1->height; i++){
361 362 363 364
		if(out[i] > 2473){
			//std::cout << "error number : " << out[i] <<std::endl;
			continue;
		}
wanghailong's avatar
wanghailong committed
365 366
		constant_template[out[i]] = true;
	}
wanghailong's avatar
wanghailong committed
367
	for (int i = 0; i < 2474; i++){
wanghailong's avatar
wanghailong committed
368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
		if (constant_template[i]==true){
			found_objnum++;
			color_labels.push_back(i);
		}
	}

	// myImage_2_opencv(temp,ttt);
	// cv::imwrite("fast_connected.jpg",ttt);
	// cv::waitKey(1);
	// delete(temp);
	//cvReleaseImage(&ttt);
	//std::cout << " found_objnum :" << found_objnum<<std::endl;

	if ( found_objnum == 1){
		free(out);
		return found_objnum-1;
	} 
	else{
		for (int n = 0; n < found_objnum; n++)
		{
			int blob_x1 = pImg1->width, blob_y1 = pImg1->height, blob_x2 = 0, blob_y2 = 0;
			for (int i = 0; i < pImg1->width; i++){
				for (int j = 0; j < pImg1->height; j++){
					if (out[i+j*pImg1->width] == color_labels.at(n)){
						if (i<blob_x1)  blob_x1 = i;
						if (j<blob_y1)  blob_y1 = j;
						if (i>blob_x2)  blob_x2 = i;
						if (j>blob_y2)  blob_y2 = j;
					}
				}
			}
			int blob_w = 0, blob_h = 0;
			blob_w = (blob_x2 - blob_x1)+1;
			blob_h = (blob_y2 - blob_y1)+1;

			//std::cout << " area : " << (int)blob_w*(int)blob_h 
					//<< " maxrea" << MAX_SFG << " minarea " << MIN_SFG <<std::endl;

			//rectangle ratio filter
			int areaThreshold_max = 0, areaThreshold_min = 0;
			if (option==0)//for moving foreground
			{
				areaThreshold_max = MAX_FG;
				areaThreshold_min = MIN_FG;
			}
			else if (option==1)
			{	
				areaThreshold_max = MAX_SFG;
				areaThreshold_min = MIN_SFG;
			}

            if(  (  ( (int)blob_w*(int)blob_h) > areaThreshold_min ) && 
                 (  ( (int)blob_w*(int)blob_h) < (float)areaThreshold_max  ) )   
			{  
wanghailong's avatar
wanghailong committed
422
				Obj_info*  element;
wanghailong's avatar
wanghailong committed
423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
				element = new Obj_info;
				element->x = blob_x1 + blob_w/2;
				element->y = blob_y1 + blob_h/2;
				element->width = blob_w;
				element->height = blob_h;
				//cvRectangle( img, cvPoint(blob_x1,blob_y1), cvPoint(blob_x2,blob_y2), CV_RGB(255,255,255), 2, 8, 0);

				if ( option == 0)	detected_result.push_back( element );
				if ( option == 1)	static_object_result.push_back( element );
            }//end of filter  
		}
		free(out);
		//std::cout << "结果数量:"<< static_object_result.size()<<std::endl;
		return found_objnum-1; 
	}//end of object checking
}


vector<Obj_info*> CBM_model::GetDetectResult()
{
	return detected_result;
}
vector<Obj_info*> CBM_model::GetStaticForegourdResult()
{
	return static_object_result;
}

myImage * CBM_model::_GetObjLfetFrame()
{
	return _Previous_Img[(FG_count+TEMPORAL_RULE/2)%TEMPORAL_RULE];
}
myImage * CBM_model::_GetPreviousFrame()
{
	return _Previous_Img[FG_count];
}
myImage * CBM_model::_GetPrevious_nFrame( int n)
{
	return _Previous_Img[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE];
}
myImage * CBM_model::_GetStaticForeground()
{
	return my_imgStatic;
}
bool ** CBM_model::GetPrevious_nForeground( int n)
{
	return Previous_FG[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE];
}

// void CBM_model::DetectPrevious_nForeground_DPM2( int n)
// {
// 	cv::Mat temp;
	
// 	temp = cv::Mat(cv::Size(new_width, new_height), CV_8UC3);
	
// 	myImage_2_opencv( _Previous_Img[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE], temp);
	
// 	for (int i = 0; i < new_width; i++)
// 	{
// 		for (int j = 0; j < new_height; j++)
// 		{
// 			if (Previous_FG[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE][i][j]==true)
// 			{
// 				myColor color; color.R = 255; color.G = 255; color.B = 255;
// 				mySet2D(dpm_gray,color,i,j);
// 			}
// 			else
// 			{
// 				myColor color; color.R = 0; color.G = 0; color.B = 0;
// 				mySet2D(dpm_gray,color,i,j);
// 			}
// 		}
// 	}
	
// 	bool foregournd_found;
// 	foregournd_found = myClustering2( dpm_gray, 0);

// 	if (foregournd_found == true)
// 	{
// 		int object_num = detected_result.size();
// 		for (int i = 0; i < object_num; i++)
// 		{
// 			int roi_x = detected_result.at(i)->x;
// 			int roi_y = detected_result.at(i)->y;
// 			int roi_w = detected_result.at(i)->width;
// 			int roi_h = detected_result.at(i)->height;
// 			cvSetImageROI(temp, cvRect(roi_x, roi_y, roi_w, roi_h));

// 			//use deformable part-based model to detect the pedestrian

// 			CvMemStorage* storage = cvCreateMemStorage(0);
// 			CvSeq* detections = 0;

// 			detections = cvLatentSvmDetectObjects(temp, detector, storage, 0.5f, -1);

// 			for( int i = 0; i < detections->total; i++ )
// 			{
// 				CvObjectDetection detection = *(CvObjectDetection*)cvGetSeqElem( detections, i );
// 				double score = detection.score;
// 				if (score>0)
// 				{
// 					CvRect bounding_box = detection.rect;

// 					cvRectangle( temp, cvPoint(bounding_box.x, bounding_box.y),
// 									cvPoint(bounding_box.x + bounding_box.width,
// 									bounding_box.y + bounding_box.height),
// 									CV_RGB(cvRound(255.0f*score),0,0), 3 );

// 					printf("x = %d, y %d, w = %d, h = %d\n",roi_x+bounding_box.x,roi_y+bounding_box.y,bounding_box.width,bounding_box.height);
// 					if ((bounding_box.x>0)&&(bounding_box.x<new_width)&&(bounding_box.x+bounding_box.width>0)&&(bounding_box.x+bounding_box.width<new_width)&&
// 						(bounding_box.y>0)&&(bounding_box.y<new_height)&&(bounding_box.y+bounding_box.height>0)&&(bounding_box.y+bounding_box.height<new_height)&&
// 						(bounding_box.width*bounding_box.height<MAX_FG)&&(bounding_box.height>bounding_box.width))
// 					{
// 						for (int x = roi_x+bounding_box.x; x <= (roi_x+bounding_box.x+bounding_box.width); x++){
// 							for (int y = roi_y+bounding_box.y; y <= (roi_y+bounding_box.y+bounding_box.height); y++){
// 								Previous_FG[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE][x][y] = true;	
// 							}
// 						}
// 					}	
// 				}
// 			}
// 			cvReleaseMemStorage( &storage );
// 			//detection end


// 			cvResetImageROI(temp);
// 		}
// 	}
	
 
// 	cvWriteFrame( _writer10, temp);
// 	// cvShowImage("DPM",temp);
// 	cvWaitKey(1);
    
// 	//cvReleaseImage(&temp);
// }

// void CBM_model::DetectPrevious_nForeground_DPM( int n)
// {
// 	IplImage * temp;
// 	temp = cvCreateImage(cv::Size(new_width, new_height), IPL_DEPTH_8U, 3);
// 	myImage_2_opencv( _Previous_Img[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE], temp);
// 	//detect_and_draw_objects( temp, detector, -1);
	
//     CvMemStorage* storage = cvCreateMemStorage(0);
//     CvSeq* detections = 0;

//     detections = cvLatentSvmDetectObjects(temp, detector, storage, 0.5f, -1);

//     for( int i = 0; i < detections->total; i++ )
//     {
//         CvObjectDetection detection = *(CvObjectDetection*)cvGetSeqElem( detections, i );
//         double score = detection.score;
// 		if (score>0)
// 		{
// 			CvRect bounding_box = detection.rect;

// 			cvRectangle( temp, cvPoint(bounding_box.x, bounding_box.y),
// 							cvPoint(bounding_box.x + bounding_box.width,
//                             bounding_box.y + bounding_box.height),
// 							CV_RGB(cvRound(255.0f*score),0,0), 3 );

// 			printf("x = %d, y %d, w = %d, h = %d\n",bounding_box.x,bounding_box.y,bounding_box.width,bounding_box.height);
// 			if ((bounding_box.x>0)&&(bounding_box.x<new_width)&&(bounding_box.x+bounding_box.width>0)&&(bounding_box.x+bounding_box.width<new_width)&&
// 				(bounding_box.y>0)&&(bounding_box.y<new_height)&&(bounding_box.y+bounding_box.height>0)&&(bounding_box.y+bounding_box.height<new_height)&&
// 				(bounding_box.width*bounding_box.height<MAX_FG)&&(bounding_box.height>bounding_box.width))
// 			{
// 				for (int x = bounding_box.x; x <= (bounding_box.x+bounding_box.width); x++){
// 					for (int y = bounding_box.y; y <= (bounding_box.y+bounding_box.height); y++){
// 						Previous_FG[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE][x][y] = true;	
// 					}
// 				}
// 			}	
// 		}
//     }
// 	cvWriteFrame( _writer10, temp);
// 	// cvShowImage("DPM",temp);
// 	cvWaitKey(1);
//     cvReleaseMemStorage( &storage );
// 	cvReleaseImage(&temp);
// }

// void CBM_model::DetectPrevious_nForeground_HOG( int n)
// {
// 	cv::Mat  temp, gray;
// 	temp = cv::Mat(cv::Size(new_width, new_height), CV_8UC3);
// 	gray = cv::Mat(cv::Size(new_width, new_height), CV_8UC1);
// 	myImage_2_opencv( _Previous_Img[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE], temp);	
// 	cv::cvtColor( temp, gray, COLOR_RGB2GRAY);
// 	hog.detectMultiScale(gray, found, 0.0, cv::Size(8,8), cv::Size(0,0), 1.04, 2, true);
	
//     // Draw positive classified windows
//     for (size_t i = 0; i < found.size(); i++)
//     {
// 		Rect r = found[i];
// 		cv::rectangle(temp, r.tl(), r.br(), cv::Scalar(0,255,0), 2);

// 			printf("x = %d, y %d, w = %d, h = %d\n",r.x,r.y,r.width,r.height);
// 			if ((r.x>0)&&(r.x<new_width)&&(r.x+r.width>0)&&(r.x+r.width<new_width)&&
// 				(r.y>0)&&(r.y<new_height)&&(r.y+r.height>0)&&(r.y+r.height<new_height))
// 			{
// 				for (int x = r.x; x <= (r.x+r.width); x++){
// 					for (int y = r.y; y <= (r.y+r.height); y++){
// 						Previous_FG[(FG_count+(TEMPORAL_RULE-n))%TEMPORAL_RULE][x][y] = true;	
// 					}
// 				}
// 			}

//     }
// 	// cvShowImage("HOG",temp);
// 	cv::waitKey(1);

// 	//cvReleaseImage(&temp);
// 	//cvReleaseImage(&gray);
// }

void CBM_model::myFSM(myImage *short_term, myImage *long_term, pixelFSM ** imageFSM, bool *** Previous_FG)
{
	myColor buffer[2];
wanghailong's avatar
wanghailong committed
641
	#pragma omp parallel for num_threads(12)
wanghailong's avatar
wanghailong committed
642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693
	for (int i = 0; i < new_width; i++){
		for (int j = 0; j < new_height; j++){
			buffer[0] = myGet2D(short_term,i,j);
			buffer[1] = myGet2D(long_term,i,j);

			imageFSM[i][j].state_pre = imageFSM[i][j].state_now;
			imageFSM[i][j].state_now = 0;

			if ((buffer[0].B==255)&&(buffer[0].G==255)&&(buffer[0].R==255)){
				imageFSM[i][j].state_now += 2;
			} 
			else{
				imageFSM[i][j].state_now = 0;
			}

			if ((buffer[1].B==255)&&(buffer[1].G==255)&&(buffer[1].R==255)){
				imageFSM[i][j].state_now++;
			} 
			else{
				imageFSM[i][j].state_now = 0;
			}

			if ((imageFSM[i][j].state_now==1)&&(imageFSM[i][j].state_pre==1)){			
				if (imageFSM[i][j].static_count==(TEMPORAL_RULE/2)){
					imageFSM[i][j].staticFG_stable = true;
				}			
				
				if (imageFSM[i][j].staticFG_candidate == true){
					imageFSM[i][j].static_count++;
				}
			}
			else
			{
				imageFSM[i][j].static_count = 0;
				imageFSM[i][j].staticFG_candidate = false;
			}

			if ((imageFSM[i][j].state_now==1)&&(imageFSM[i][j].state_pre==3))
			{
				imageFSM[i][j].staticFG_candidate = true;
			}

			if (imageFSM[i][j].state_now==3)
				Previous_FG[FG_count][i][j] = true;
			else
				Previous_FG[FG_count][i][j] = false;
		}
	}
}

void CBM_model::myConvert2Img(bool **Array, myImage *output)
{
wanghailong's avatar
wanghailong committed
694
	#pragma omp parallel for num_threads(12)
wanghailong's avatar
wanghailong committed
695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713
	for (int i = 0; i < new_width; i++){
		for (int j = 0; j < new_height; j++){
			if ( Array[i][j] == true ){
				myColor a; a.B = 255; a.G = 0; a.R = 0;
				mySet2D( output, a, i, j);
			}
			else{
				myColor a; a.B = 0; a.G = 0; a.R = 0;
				mySet2D( output, a, i, j);
			}
		}
	}
}

void CBM_model::myConvertFSM2Img(pixelFSM **Array, myImage *Candidate_Fg, myImage *Static_Fg )
{
	myColor color1, color2;
	color1.B = 0; color1.G = 0; color1.R = 255;
	color2.B = 0; color2.G = 200; color2.R = 255;
wanghailong's avatar
wanghailong committed
714
	#pragma omp parallel for num_threads(12)	
wanghailong's avatar
wanghailong committed
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751
	for (int i = 0; i < new_width; i++){
		for (int j = 0; j < new_height; j++){
			if ( Array[i][j].staticFG_candidate == true )
				mySet2D(Candidate_Fg,color1,i,j);
			else{
				myColor a; a.B = 0; a.G = 0; a.R = 0;
				mySet2D(Candidate_Fg,a,i,j);
			}

			if ( Array[i][j].staticFG_stable == true )
				mySet2D(Static_Fg,color2,i,j);
			else{
				myColor a; a.B = 0; a.G = 0; a.R = 0;
				mySet2D(Static_Fg,a,i,j);	
			}
		}
	}
}


int CBM_model::check_foreground2( myImage * img)
{
	int foregroud = 0;
	myColor a;
	for (int i = 0; i < img->width; i++)
	{
		for (int j = 0; j < img->height; j++)
		{
			a = myGet2D(img, i, j);
			if ((a.B >= 100)||(a.G >= 100)||(a.R >= 100))
			{
				foregroud++;
			}
		}
	}
	return foregroud;
}