//--------------------------------------------------------------------------------
void ofxCvGrayscaleImage::setFromCvColorImage( ofxCvColorImage& mom ) {
	if( matchingROI(getROI(), mom.getROI()) ) {
		cvCvtColor( mom.getCvImage(), cvImage, CV_RGB2GRAY );
        flagImageChanged();
	} else {
        ofLog(OF_LOG_ERROR, "in =, ROI mismatch");
	}
}
void ofxBackground::update(ofxCvColorImage& input){
	float now = ofGetElapsedTimeMillis();
	
		// get width/height disregarding ROI
    IplImage* ipltemp = input.getCvImage();
    _width = ipltemp->width;
    _height = ipltemp->height;
	
	if( inputCopy.getWidth() == 0 ) {
		allocate( _width, _height );
	} else if( inputCopy.getWidth() != _width || inputCopy.getHeight() != _height ) {
			// reallocate to new size
		clear();
		allocate( _width, _height );
	} else { //don't do anything unless we have allocated! (and therefore set timeStartedLearning to a safe, non zero value)
		
		inputCopy = input;
		inputCopy.setROI( input.getROI() );
		yuvImage.setROI( input.getROI() ); //pass on ROI'ness
		
		yuvImage.setFromPixels(inputCopy.getPixels(), _width, _height);
		yuvImage.convertRgbToYuv();	
		
		if((now-timeStartedLearning) < LEARNING_TIME){
				//then we should be learning
				//LEARNING THE AVERAGE AND AVG DIFF BACKGROUND
			accumulateBackground(inputCopy.getCvImage());
				//LEARNING THE CODEBOOK BACKGROUND
			pColor = (uchar *)((yuvImage.getCvImage())->imageData);
			for(int c=0; c<imageLen; c++)
			{
				cvupdateCodeBook(pColor, cB[c], cbBounds, nChannels);
				pColor += 3;
			}
			
				//TODO: clear stale entries
			
			bStatsDone = false;
			bLearning = true;
		}else {
				//its either time to do stats or not
			bLearning = false;
			if(!bStatsDone){
					//do the stats, just the once
				createModelsfromStats(); //create the background model
				bStatsDone = true;
			}else {
					//learn as normal, find the foreground if any
						//FIND FOREGROUND BY AVG METHOD:
					backgroundDiff(inputCopy.getCvImage(),ImaskAVG);
					cvCopy(ImaskAVG,ImaskAVGCC);
					cvconnectedComponents(ImaskAVGCC);
						//FIND FOREGROUND BY CODEBOOK METHOD
					uchar maskPixelCodeBook;
					pColor = (uchar *)((yuvImage.getCvImage())->imageData); //3 channel yuv image
					uchar *pMask = (uchar *)((ImaskCodeBook)->imageData); //1 channel image
					for(int c=0; c<imageLen; c++)
					{
						maskPixelCodeBook = cvbackgroundDiff(pColor, cB[c], nChannels, minMod, maxMod);
						*pMask++ = maskPixelCodeBook;
						pColor += 3;
					}
						//This part just to visualize bounding boxes and centers if desired
					cvCopy(ImaskCodeBook,ImaskCodeBookCC);	
					cvconnectedComponents(ImaskCodeBookCC);				
				
					//TODO: update the learned background pixels....
					//TODO: clear stale codebook entries on a much slower frequency
			}

		}
		
		backgroundAverage = ImaskAVG;
		backgroundAverageConnectedComponents = ImaskAVGCC;
		backgroundCodebook = ImaskCodeBook;
		backgroundCodeBookConnectedComponents = ImaskCodeBookCC;	
	}
}