Exemplo n.º 1
0
	int LocalisationPupil::estimateThreshold(IplImage *im){
		IplImage* im2 = cvCloneImage(im);
		
		// supprimer les bruits
		cvSmooth( im2, im2, CV_GAUSSIAN,3 ,3);
		
		int bins = 50;
		int index_min,index_max;
		int hsize[] = {bins};
		float max_value = 0, min_value = 0;
		//ranges - grayscale 0 to 50
		float xranges[] = { 0, 50 };
		float* ranges[] = { xranges };
		CvHistogram* hist = cvCreateHist( 1, hsize, CV_HIST_ARRAY, ranges,1);
		cvCalcHist( &im2, hist, 0, NULL);
		cvGetMinMaxHistValue( hist, &min_value, &max_value,&index_min,&index_max);
		
		int thresh;
		
		thresh = index_max+10;
		
		cvReleaseImage( &im2);
		
		return thresh;
	}
Exemplo n.º 2
0
Mask* Histogram::representInMask()
{
	int h_bins = 30, s_bins = 32; 
	int scale = 10;
	IplImage* hist_image = cvCreateImage(cvSize( h_bins * scale, s_bins * scale ), 
                                         8, 
                                         3); 
	cvZero( hist_image );
	
	/* populate our visualization with little gray squares. */
	float max_value = 0;
	cvGetMinMaxHistValue( m_histogram, 0, &max_value, 0, 0 );
	
	for( int h = 0; h < h_bins; h++ ) {
		for( int s = 0; s < s_bins; s++ ) {
			float bin_val = cvQueryHistValue_2D( m_histogram, h, s );
			int intensity = cvRound( bin_val * 255 / max_value );
			cvRectangle(hist_image, 
                                    cvPoint( h*scale, s*scale ),
                                    cvPoint( (h+1)*scale - 1, (s+1)*scale - 1),
                                    CV_RGB(intensity,intensity,intensity),
                                    CV_FILLED);
		}
	}
	
	return new Image(hist_image);
}
Exemplo n.º 3
0
// startTracking()
//
void startTracking(IplImage * pImg, CvRect pHandRect,KalmanFilter &kfilter)
{
	float maxVal = 0.f;

	// Make sure internal data structures have been allocated
	if( !pHist ) createTracker(pImg);

	// Create a new hue image
	updateHueImage(pImg);

    if(!((pHandRect.x<0)||(pHandRect.y<0)||((pHandRect.x+pHandRect.width)>pImg->width)||((pHandRect.y+pHandRect.height)>pImg->height))) {

	// Create a histogram representation for the hand
    cvSetImageROI( pHueImg, pHandRect );
    cvSetImageROI( pMask,   pHandRect );
    cvCalcHist( &pHueImg, pHist, 0, pMask );
    cvGetMinMaxHistValue( pHist, 0, &maxVal, 0, 0 );
    cvConvertScale( pHist->bins, pHist->bins, maxVal? 255.0/maxVal : 0, 0 );
    cvResetImageROI( pHueImg );
    cvResetImageROI( pMask );

	}
	// Store the previous hand location
	prevHandRect =pHandRect;
	prevHandRect2 =pHandRect;

	//Pass the hand location to kalman initializer
	kfilter.predictionBegin(prevHandRect);
	
}
Exemplo n.º 4
0
IplImage* DrawHistogram(CvHistogram *hist, float scaleX=2, float scaleY=2){
    float histMax = 0;
    cvGetMinMaxHistValue(hist, 0, &histMax, 0, 0);
    IplImage* imgHist = cvCreateImage(cvSize(256*scaleX, 64*scaleY), 8 ,1);

    cvZero(imgHist); //clear all elements to be zeros.
    cvSet(imgHist, cvScalar(255)); //set all to be 255; white background.

    for(int i=0; i< 255; i++) {
    	//float histValue = cvQueryHistValue_1D(hist, i); //not working, use the one below instead.
    	float histValue = cvGetReal1D(hist->bins, i);
        //float nextValue = cvQueryHistValue_1D(hist, i+1); //not working.
        float nextValue = cvGetReal1D(hist->bins, i+1);

        CvPoint pt1 = cvPoint(i*scaleX, 64*scaleY);
        CvPoint pt2 = cvPoint(i*scaleX+scaleX, 64*scaleY);
        CvPoint pt3 = cvPoint(i*scaleX+scaleX, (64-nextValue*64/histMax)*scaleY);
        CvPoint pt4 = cvPoint(i*scaleX, (64-histValue*64/histMax)*scaleY);

        int numPts = 5;
        CvPoint pts[] = {pt1, pt2, pt3, pt4, pt1};
        cvFillConvexPoly(imgHist, pts, numPts, cvScalar(0)); //filled with black color.
    }
    return imgHist;
}
Exemplo n.º 5
0
// ------------------------------------------------------------------------
void LABHistogram2D::Draw(CDC* pDC) {
	CPen pen(PS_SOLID, 1, RGB(0, 0, 0));
	CPen* pOldPen = pDC->SelectObject(&pen);

	float min_value = 0, max_value = 0;
	cvGetMinMaxHistValue( h, &min_value, &max_value, 0, 0 );
	CRect box;
	pDC->GetWindow()->GetWindowRect(&box);
	int iscale = box.Width()/a_bins;
	int jscale = box.Height()/b_bins;

	for(int i=0; i<a_bins;i++ )
	{
		for(int j=0; j<b_bins;j++ )
		{
			float bin_val = cvQueryHistValue_2D( h, i, j );
			int intensity = cvRound((bin_val-min_value)*255/(max_value-min_value));
			CBrush fill;
			fill.CreateSolidBrush(RGB(0,0,intensity));   
			CRect r(i*iscale, j*jscale, (i+1)*iscale - 1, (j+1)*jscale - 1);
			pDC->FillRect(&r, &fill);
		}
	}
	pDC->SelectObject(pOldPen);
}
Exemplo n.º 6
0
HandDetect::HandDetect()
{
	numColorBins = 256;
	max_val = 0.f;
	hand1 = cvLoadImage("hand.png");
	hand2 = cvLoadImage("hand2.png");
	hist1 = cvCreateHist(1, &numColorBins, CV_HIST_ARRAY);
	hist2 = cvCreateHist(1, &numColorBins, CV_HIST_ARRAY);
	
	rad=0;
	vmin=10, vmax=256, smin=30;

	capture = cvCaptureFromCAM(0);
	setImage();
	backproject = cvCreateImage(cvGetSize(image), 8, 1);
	gray = cvCreateImage(cvGetSize(image), 8, 1);
	track_window = cvRect((int)image->width/2, (int)image->height/2, 1, 1);
	track_box.center.x=-1;
	track_box.center.y=-1;

	hsvHand1 = cvCreateImage(cvGetSize(hand1), 8, 3);
	mskHand1 = cvCreateImage(cvGetSize(hand1), 8, 1);
	hueHand1 = cvCreateImage(cvGetSize(hand1), 8, 1);

	hsvHand2 = cvCreateImage(cvGetSize(hand2), 8, 3);
	mskHand2 = cvCreateImage(cvGetSize(hand2), 8, 1);
	hueHand2 = cvCreateImage(cvGetSize(hand2), 8, 1);	

	cvCvtColor(hand1, hsvHand1, CV_RGB2HSV);
	cvInRangeS(hsvHand1, cvScalar(0, smin, MIN(vmin, vmax), 0), cvScalar(180, 256, MAX(vmin, vmax), 0), mskHand1);
	cvSplit(hsvHand1, hueHand1, 0, 0, 0);

	cvCalcHist(&hueHand1, hist1, 0, mskHand1);
	cvGetMinMaxHistValue(hist1, 0, &max_val, 0, 0);
	cvConvertScale(hist1->bins, hist1->bins, max_val ? 255. / max_val : 0., 0);


	cvCvtColor(hand2, hsvHand2, CV_RGB2HSV);
	cvInRangeS(hsvHand2, cvScalar(0, smin, MIN(vmin, vmax), 0), cvScalar(180, 256, MAX(vmin, vmax), 0), mskHand2);
	cvSplit(hsvHand2, hueHand2, 0, 0, 0);

	cvCalcHist(&hueHand2, hist2, 0, mskHand2);
	cvGetMinMaxHistValue(hist2, 0, &max_val, 0, 0);
	cvConvertScale(hist2->bins, hist2->bins, max_val ? 255. / max_val : 0., 0);
}
int main( int argc, char** argv )
{
    IplImage *src = 0;
    IplImage *histimg = 0;
    CvHistogram *hist = 0;
    
    int hbins = 255;     // 划分HIST的个数,越高越精确
	int maxcount = 255;
    float hranges_arr[] = {0,maxcount};//
    float* hranges = hranges_arr;
    int bin_w;  
    float max_val;
    int i;
    
    if((src=cvLoadImage("../cvtest/7newsample.jpg", CV_LOAD_IMAGE_GRAYSCALE)) == NULL)  // force to gray image
        return -1;
    
    cvNamedWindow( "Histogram", 0 );
    cvNamedWindow( "src", 0);
    
    hist = cvCreateHist( 1, &hbins, CV_HIST_ARRAY, &hranges, 1 );  // 计算直方图
    histimg = cvCreateImage( cvSize(320,200), 8, 3 );
    cvZero( histimg );
    cvCalcHist( &src, hist, 0, 0 ); // 计算直方图
   float min_val = 0;
    cvGetMinMaxHistValue( hist, &min_val, &max_val, 0, 0 );  // 只找最大值
	printf("max_val:%.4f,min:%.4f\n",max_val,min_val);
cvConvertScale( hist->bins, hist->bins, max_val ? 255. / max_val : 0., 0 ); // 缩放 bin 到区间 [0,255] 
    cvZero( histimg );
    bin_w = histimg->width / hbins;  // hbins: 条的个数,则 bin_w 为条的宽度
    
    // 画直方图
    for( i = 0; i < hbins; i++ )
    {
        double val = ( cvGetReal1D(hist->bins,i)/*255份中的几份*/*histimg->height/maxcount );
		
        CvScalar color = CV_RGB(255,255,0); //(hsv2rgb(i*180.f/hbins);
        cvRectangle( histimg, cvPoint(i*bin_w,histimg->height),
            cvPoint((i+1)*bin_w,(int)(histimg->height - val)),
            color, 1, 8, 0 );
		printf("(%d,%d),(%d,%d)\n",i*bin_w,histimg->height,(i+1)*bin_w,(int)(histimg->height - val));
    }
    
    cvShowImage( "src", src);
    cvShowImage( "Histogram", histimg );
    cvWaitKey(0);

    cvDestroyWindow("src");
    cvDestroyWindow("Histogram");
    cvReleaseImage( &src );
    cvReleaseImage( &histimg );
    cvReleaseHist ( &hist );
    
    return 0; 
}
Exemplo n.º 8
0
void CvAdaptiveSkinDetector::Histogram::mergeWith(CvAdaptiveSkinDetector::Histogram *source, double weight)
{
    float myweight = (float)(1-weight);
    float maxVal1 = 0, maxVal2 = 0, *f1, *f2, ff1, ff2;

    cvGetMinMaxHistValue(source->fHistogram, NULL, &maxVal2);

    if (maxVal2 > 0 )
    {
        cvGetMinMaxHistValue(fHistogram, NULL, &maxVal1);
        if (maxVal1 <= 0)
        {
            for (int i = 0; i < HistogramSize; i++)
            {
                f1 = (float*)cvPtr1D(fHistogram->bins, i);
                f2 = (float*)cvPtr1D(source->fHistogram->bins, i);
                (*f1) = (*f2);
            }
        }
        else
        {
            for (int i = 0; i < HistogramSize; i++)
            {
                f1 = (float*)cvPtr1D(fHistogram->bins, i);
                f2 = (float*)cvPtr1D(source->fHistogram->bins, i);

                ff1 = ((*f1)/maxVal1)*myweight;
                if (ff1 < 0)
                    ff1 = -ff1;

                ff2 = (float)(((*f2)/maxVal2)*weight);
                if (ff2 < 0)
                    ff2 = -ff2;

                (*f1) = (ff1 + ff2);

            }
        }
    }
};
Exemplo n.º 9
0
void Draw_hist(IplImage* img,CvRect Rect)
{
    if(Rect.x<=0||Rect.y<=0||Rect.width<=0||Rect.height<=0)
    {
        return;
    }   
    cvSetImageROI(img,Rect);
    IplImage* hsv=cvCreateImage(cvGetSize(img),8,3);
    IplImage* h_plane=cvCreateImage(cvGetSize(img),8,1);
    IplImage* s_plane=cvCreateImage(cvSize(Rect.width,Rect.height),8,1);
    IplImage* v_plane=cvCreateImage(cvSize(Rect.width,Rect.height),8,1);
    IplImage* planes[]={h_plane,s_plane};
    int h_bins=16,s_bins=8;
    int hist_size[]={h_bins,s_bins};
    float h_ranges[]={0,180};
    float s_ranges[]={0,255};
    float* ranges[]={h_ranges,s_ranges};
    cvCvtColor(img,hsv,CV_BGR2HSV);
    cvResetImageROI(img);
    cvSplit(hsv,h_plane,s_plane,v_plane,0);
    CvHistogram *hist=cvCreateHist(2,hist_size,CV_HIST_ARRAY,ranges,1);
    cvCalcHist(planes,hist,0,0);
    float max_value;
    cvGetMinMaxHistValue(hist,0,&max_value,0,0);
    int height=480;
    int width=(h_bins*s_bins*6);
    IplImage* hist_img=cvCreateImage(cvSize(width,height),8,3);
    cvZero(hist_img);
    IplImage* hsv_color=cvCreateImage(cvSize(1,1),8,3);
    IplImage* rgb_color=cvCreateImage(cvSize(1,1),8,3);
    int bin_w=width/(h_bins*s_bins);
    for(int h=0;h<h_bins;h++)
    {
        for(int s=0;s<s_bins;s++)
        {
            int i=h*s_bins+s;
            //获取直方图中统计的次数,计算显示在图像中的高度
            float bin_val=cvQueryHistValue_2D(hist,h,s);
            int intensity=cvRound(bin_val*height/max_value);

            cvSet2D(hsv_color,0,0,cvScalar(h*180.f/h_bins,s*255.f/s_bins,255,0));
            cvCvtColor(hsv_color,rgb_color,CV_HSV2BGR);
            CvScalar color=cvGet2D(rgb_color,0,0);

            cvRectangle(hist_img,cvPoint(i*bin_w,height),cvPoint((i+1)*bin_w,height-intensity),color,-1,8,0);


        }
    }
    cvNamedWindow("H-S Histogram",1);
    cvShowImage("H-S Histogram",hist_img);
}
Exemplo n.º 10
0
void CV_MinMaxHistTest::run_func(void)
{
    if( hist_type != CV_HIST_ARRAY && test_cpp )
    {
        cv::SparseMat h((CvSparseMat*)hist[0]->bins);
        double _min_val = 0, _max_val = 0;
        cv::minMaxLoc(h, &_min_val, &_max_val, min_idx, max_idx );
        min_val = (float)_min_val;
        max_val = (float)_max_val;
    }
    else
        cvGetMinMaxHistValue( hist[0], &min_val, &max_val, min_idx, max_idx );
}
Exemplo n.º 11
0
int main(int argc, char* argv[])
{
    cvNamedWindow("Original",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("Binaria",CV_WINDOW_AUTOSIZE);
    cvNamedWindow("Histograma",CV_WINDOW_AUTOSIZE);
    imatge = cvLoadImage("C:\\EUPMT\\Projects\\OpenCV_Contours\\exemple03.jpg", 0);
    IplImage* binaria = cvCreateImage(cvGetSize(imatge), 8, 1);
    imgHistogram = 0;


    int hsize[] = {bins};
    float max_value = 0, min_value = 0;
    float xranges[] = { 0, 256 };
    float* ranges[] = { xranges };

    hist = cvCreateHist( 1, hsize, CV_HIST_ARRAY, ranges,1);
    cvCalcHist( &imatge, hist, 0, NULL);
    cvGetMinMaxHistValue( hist, &min_value, &max_value);

    dibuixarHistograma(max_value);


    int llindar = llindar_gaussian(imatge, hist);

    int step =imatge->widthStep;
    int canals = imatge->nChannels;
    uchar* imgData = (uchar*) imatge->imageData;
    uchar* imgDataBinaria = (uchar*) binaria->imageData;

    for( int i = 0; i < imatge->height; i++)
        for( int j = 0; j < imatge->width; j++)
        {
            if((imgData[i*step+j*canals]) > llindar)
            {
                imgDataBinaria[i*binaria->widthStep+j*binaria->nChannels]=0;
            }
            else
            {
                imgDataBinaria[i*binaria->widthStep+j*binaria->nChannels]=255;
            }
        }


    cvShowImage("Original", imatge);
    cvShowImage("Histograma", imgHistogram);
    cvShowImage("Binaria", binaria);
    cvWaitKey(0);
    cvDestroyAllWindows();
    return 0;
}
Exemplo n.º 12
0
void maxHSV(IplImage *img, No *imagem){
	/* variaveis do histograma */
	int numBins = 256;
	float range[] = {0, 255};
	float *ranges[] = {range};
	
	/* cria um histograma */
	CvHistogram *hist = cvCreateHist(1, &numBins, CV_HIST_ARRAY, ranges, 1);
	cvClearHist(hist);
	
	/* aloca as imagens auxiliares */
	IplImage *imgHSV = cvCreateImage(cvGetSize(img), 8, 3);
	IplImage *imgH = cvCreateImage(cvGetSize(img), 8, 1);
	IplImage *imgS = cvCreateImage(cvGetSize(img), 8, 1);
	IplImage *imgV = cvCreateImage(cvGetSize(img), 8, 1);

	cvCvtColor(img, imgHSV, CV_BGR2HSV);			// converte a img (RGB) para imgHSV (HSV)
	cvSplit(imgHSV, imgH, imgS, imgV, NULL);		// separa os canais da imgHSV
	
	cvCalcHist(&imgH, hist, 0, 0);					// calcula o histograma da imgH
	cvGetMinMaxHistValue(hist, NULL, NULL, NULL, &imagem->max_h); // coleta a cor dominante
	cvClearHist(hist);
	
	cvCalcHist(&imgS, hist, 0, 0);
	cvGetMinMaxHistValue(hist, NULL, NULL, NULL, &imagem->max_s);
	cvClearHist(hist);
	
	cvCalcHist(&imgV, hist, 0, 0);
	cvGetMinMaxHistValue(hist, NULL, NULL, NULL, &imagem->max_v);
	cvClearHist(hist);
	
	/* libera as imagens auxiliares */
	cvReleaseImage(&imgHSV);
	cvReleaseImage(&imgH);
	cvReleaseImage(&imgS);
	cvReleaseImage(&imgV);
}
IplImage* CamShiftPatch::drawHistImg(CvRect selectROI, CvScalar maskRange)
{
	IplImage* hue = 0;
	hue = cvCreateImage(cvGetSize(originImage), 8, 1);
	IplImage *mask = getInRangeMask(maskRange, hue);//CvScalar 0->Vmin  1->Vmax  2->Smin

	//---設定ROI和畫出直方圖---

	float max_val = 0.f;
	cvSetImageROI(hue, selectROI);
	cvSetImageROI(mask, selectROI);

	
	int hdims = 48; //劃分HIST的個數,越高越精確 
	float hranges_arr[] = { 0, 180 }; //直方圖範圍
	float* hranges = hranges_arr;//指向值方圖範圍
	histogram = cvCreateHist(1, &hdims, CV_HIST_ARRAY, &hranges, 1); //設定直方圖的格式
	cvCalcHist(&hue, histogram, 0, mask); //以hue資訊 得到直方圖 (只有ROI部分的資訊)
	cvGetMinMaxHistValue(histogram, 0, &max_val, 0, 0); //只找最大值 
	cvConvertScale(histogram->bins, histogram->bins, max_val ? 255. / max_val : 0., 0); //縮放bin到區間[0,255]  
	//input      output        尺度放大或縮小         全部顏色的增減       
	cvResetImageROI(hue); // remove ROI  
	cvResetImageROI(mask);
	//track_window = selectROI; //搜索窗即一開始ROI框

	//----畫直方圖hist to histimg------------------

	IplImage* histimg = cvCreateImage(cvSize(320, 200), 8, 3);  //直方圖顯示空間,三通道
	cvZero(histimg); //置背景為黑色

	int bin_w = 0;
	bin_w = histimg->width / hdims; // hdims:條的個數,則bin_w為條的寬度  

	for (int i = 0; i < hdims; i++)
	{
		int val = cvRound(cvGetReal1D(histogram->bins, i)*histimg->height / 255);  //cvGetReal1D(直方條高度,第幾條) 
		CvScalar color = hsv2rgb(i*180.f / hdims); //在RGB空間上,直方圖每條的顏色計算   180/hdims表示每一格多寬 , i*180/hdims代表到橫軸的哪個位置了 由那個位置的顏色資訊轉換成RGB  
		cvRectangle(histimg, cvPoint(i*bin_w, histimg->height), cvPoint((i + 1)*bin_w, histimg->height - val), color, -1, 8, 0);//畫出不同顏色的直方長條來
	}
	//---設定ROI和畫出直方圖 end---
	IplImage* returnImg = nullptr;
	returnImg = cvCloneImage(histimg);

	cvReleaseImage(&hue);
	cvReleaseImage(&mask);
	cvReleaseImage(&histimg);

	return returnImg;
}
Exemplo n.º 14
0
void COpenCVMFCView::OnImageHistogram()
{
	// TODO: Add your command handler code here

	IplImage *src;
	IplImage *histimg = 0;
	CvHistogram *hist = 0;

	int hdims = 256;     // Divide Number of HIST, the more the accurator
	float hranges_arr[] = {0,255};
	float* hranges = hranges_arr;
	int bin_w;  
	float max_val;
	int i;

	src = workImg;

	cvNamedWindow( "Histogram", 0 );

	hist = cvCreateHist( 1, &hdims, CV_HIST_ARRAY, &hranges, 1 );  // Create Hist
	histimg = cvCreateImage( cvSize(320,200), 8, 3 );
	cvZero( histimg );
	cvCalcHist( &src, hist, 0, 0 ); // Caculate Hist
	cvGetMinMaxHistValue( hist, 0, &max_val, 0, 0 );  // just wanna the Max
	cvConvertScale( hist->bins, hist->bins, 
		max_val ? 255. / max_val : 0., 0 ); // resize bin to [0,255] 
	cvZero( histimg );
	bin_w = histimg->width / hdims;

	// Draw It
	for( i = 0; i < hdims; i++ )
	{
		double val = ( cvGetReal1D(hist->bins,i)*histimg->height/255 );
		CvScalar color = CV_RGB(255,255,0); //(hsv2rgb(i*180.f/hdims);
		cvRectangle( histimg, cvPoint(i*bin_w,histimg->height),
			cvPoint((i+1)*bin_w,(int)(histimg->height - val)),
			color, 1, 8, 0 );
	}

	cvShowImage( "Histogram", histimg );

	cvReleaseImage( &histimg );
	cvReleaseHist ( &hist );
	cvWaitKey(0);

	cvDestroyWindow("Histogram");
}
Exemplo n.º 15
0
void Widget::zhifangtu(IplImage *hist_img)
{
    IplImage *histimg = 0;
    CvHistogram *hist = 0;                    //直方图
    int hdims=255;
     float hranges_arr[] = {0,255};
        float* hranges = hranges_arr;
        int bin_w;
        float max_val,min_val;
        int i;

        cvNamedWindow( "Histogram", 0 );
//        cvNamedWindow( "src", 0);
hist = cvCreateHist( 1, &hdims, CV_HIST_ARRAY, &hranges, 1 );   //创建直方图
histimg = cvCreateImage( cvSize(320,200), 8, 3 );
    cvZero( histimg );                                            //清零

    cvCalcHist( &hist_img, hist, 0, 0 );                               // 计算直方图,即每个bin的大小
    cvGetMinMaxHistValue( hist, &min_val, &max_val, 0, 0 );              // 只找最大值
    cvThreshHist(hist,50);
//qDebug("max:%4.2f",max_val);
//qDebug("min:%4.2f",min_val);
 cvConvertScale( hist->bins,hist->bins, max_val ? 255. / max_val : 0., 0 );             // 缩放 bin 到区间 [0,255]

    cvZero( histimg );
    bin_w = histimg->width / hdims;                               // hdims: 直方图竖条的个数,则 bin_w 为条的宽度

    // 画直方图
    for( i = 0; i < hdims; i++ )
    {
        double val = ( cvGetReal1D(hist->bins,i)*histimg->height/255 );
        CvScalar color = CV_RGB(255,255,0);                                 //(hsv2rgb(i*180.f/hdims);
        cvRectangle( histimg, cvPoint(i*bin_w,histimg->height),
            cvPoint((i+1)*bin_w,(int)(histimg->height - val)),
            color, 1, 8, 0 );
    }

//    cvShowImage( "src", hue);
        cvShowImage( "Histogram", histimg );
cv::waitKey(0);
//    cvDestroyWindow("src");
    cvDestroyWindow("Histogram");
    //cvReleaseImage( &src );
    cvReleaseImage( &histimg );
    cvReleaseHist ( &hist );
}
Exemplo n.º 16
0
void initTracking(camshift * cs, IplImage * img, CvRect * faceRect)
{
  float maxVal = 0.f;

  updateHueImage(cs, img);

  cvSetImageROI( cs->hueImg, *faceRect );
  cvSetImageROI( cs->mask,   *faceRect );
  cvCalcHist( &cs->hueImg, cs->hist, 0, cs->mask );
  cvGetMinMaxHistValue( cs->hist, 0, &maxVal, 0, 0 );
  cvConvertScale( cs->hist->bins, cs->hist->bins,
      maxVal? 255.0/maxVal : 0, 0 );
  cvResetImageROI( cs->hueImg );
  cvResetImageROI( cs->mask );

  cs->prevFaceRect = *faceRect;
}
Exemplo n.º 17
0
IplImage* drawHistogram(CvHistogram* hist)
{
	// Scale
	int scaleX = 2;
	int scaleY = 2;


	float histMax = 0;

	cvGetMinMaxHistValue(hist, 0, &histMax, 0, 0);

	// create blank image
	IplImage* imgHist = cvCreateImage(cvSize(256*scaleX, 64*scaleY), 8 ,1);
	cvZero(imgHist);


	// iterate thro' bins and render out graphics...
	int i=0;
	for(i=0;i<255;i++)
	    {
	        float histValue = cvQueryHistValue_1D(hist, i);
	        float nextValue = cvQueryHistValue_1D(hist, i+1);

	        CvPoint pt1 = cvPoint(i*scaleX, 64*scaleY);
	        CvPoint pt2 = cvPoint(i*scaleX+scaleX, 64*scaleY);
	        CvPoint pt3 = cvPoint(i*scaleX+scaleX, (64-nextValue*64/histMax)*scaleY);
	        CvPoint pt4 = cvPoint(i*scaleX, (64-histValue*64/histMax)*scaleY);

	        int numPts = 5;
	        CvPoint pts[] = {pt1, pt2, pt3, pt4, pt1};

	        cvFillConvexPoly(imgHist, pts, numPts, cvScalar(255,0,0,0),8,0);
	    }






	return imgHist;


}
Exemplo n.º 18
0
// ######################################################################
void VisualTracker::setTargets(const Image<byte>& grey, const Image<byte>& target)
{
#ifdef HAVE_OPENCV
  if (itsInitTracker)
    initTracker(grey.getDims());

  IplImage* currentImg = img2ipl(grey);

  cvCalcHist( &currentImg, itsObjectHist );

  float max_val = 0.f;
  cvGetMinMaxHistValue(itsObjectHist, 0, &max_val, 0, 0 );
  cvConvertScale( itsObjectHist->bins, itsObjectHist->bins, max_val ? 255. / max_val : 0., 0 );



  itsTargetTempl = target;
#endif
}
Exemplo n.º 19
0
/* Create a camshift tracked object from a region in image. */
TrackedObj* FaceBl0r::create_tracked_object (IplImage* image, CvRect* region) {
  TrackedObj* obj;
  
  //allocate memory for tracked object struct
  if((obj = (TrackedObj *) malloc(sizeof *obj)) != NULL) {
    //create-image: size(w,h), bit depth, channels
    obj->hsv  = cvCreateImage(cvGetSize(image), 8, 3);
    obj->mask = cvCreateImage(cvGetSize(image), 8, 1);
    obj->hue  = cvCreateImage(cvGetSize(image), 8, 1);
    obj->prob = cvCreateImage(cvGetSize(image), 8, 1);

    int hist_bins = 30;           //number of histogram bins
    float hist_range[] = {0,180}; //histogram range
    float* range = hist_range;
    obj->hist = cvCreateHist(1,             //number of hist dimensions
                             &hist_bins,    //array of dimension sizes
                             CV_HIST_ARRAY, //representation format
                             &range,        //array of ranges for bins
                             1);            //uniformity flag
  }
  
  //create a new hue image
  update_hue_image(image, obj);

  float max_val = 0.f;
  
  //create a histogram representation for the face
  cvSetImageROI(obj->hue, *region);
  cvSetImageROI(obj->mask, *region);
  cvCalcHist(&obj->hue, obj->hist, 0, obj->mask);
  cvGetMinMaxHistValue(obj->hist, 0, &max_val, 0, 0 );
  cvConvertScale(obj->hist->bins, obj->hist->bins,
                 max_val ? 255.0/max_val : 0, 0);
  cvResetImageROI(obj->hue);
  cvResetImageROI(obj->mask);
  
  //store the previous face location
  obj->prev_rect = *region;

  return obj;
}
Exemplo n.º 20
0
void CamShift::CalcHistogram(const ImgBgr& img, const CRect& sel)
{
  selection.x = sel.left;
  selection.y = img.Height()-sel.bottom-1;
  selection.width = sel.Width();
  selection.height = sel.Height();

  cvCopy(ImgIplImage(img), image, 0 );
  cvCvtColor( image, hsv, CV_BGR2HSV );
  cvFlip(hsv,hsv,0);
  //cvSaveImage("hsv.bmp", hsv);
  //cvSaveImage("img.bmp", image);
  int _vmin = vmin, _vmax = vmax;
  cvInRangeS( hsv, cvScalar(0,smin,MIN(_vmin,_vmax),0),
  cvScalar(180,256,MAX(_vmin,_vmax),0), mask );
  cvSplit( hsv, hue, 0, 0, 0 );
  float max_val = 0.f;
  cvSetImageROI(hue, selection );
  cvSetImageROI( mask, selection );
  cvCalcHist( &hue, hist, 0, mask );
  cvGetMinMaxHistValue( hist, 0, &max_val, 0, 0 );
  cvConvertScale( hist->bins, hist->bins, max_val ? 255. / max_val : 0., 0 );
  cvResetImageROI( hue );
  cvResetImageROI( mask );
  track_window = selection;
//  cvZero( histimg );
//  int bin_w = histimg->width / hdims;
//  for(int i = 0; i < hdims; i++ )
//  {
//    int a = cvGetReal1D(hist->bins,i);
//    int val = cvRound( cvGetReal1D(hist->bins,i)*histimg->height/255 );
//    CvScalar color = hsv2rgb(i*180.f/hdims);
//    cvRectangle( histimg, cvPoint(i*bin_w,histimg->height),
//      cvPoint((i+1)*bin_w,histimg->height - val),
//      color, -1, 8, 0 );
//  }
//  cvNamedWindow( "Histogram", 1 );
//  
//  cvShowImage( "Histogram", histimg );
}
Exemplo n.º 21
0
//////////////////////////////////
// startTracking()
//
void startTracking(IplImage * pImg, CvRect * pFaceRect)
{
	float maxVal = 0.f;

	// Make sure internal data structures have been allocated
	if( !pHist ) createTracker(pImg);

	// Create a new hue image
	updateHueImage(pImg);

	// Create a histogram representation for the face
    cvSetImageROI( pHueImg, *pFaceRect );
    cvSetImageROI( pMask,   *pFaceRect );
    cvCalcHist( &pHueImg, pHist, 0, pMask );
    cvGetMinMaxHistValue( pHist, 0, &maxVal, 0, 0 );
    cvConvertScale( pHist->bins, pHist->bins, maxVal? 255.0/maxVal : 0, 0 );
    cvResetImageROI( pHueImg );
    cvResetImageROI( pMask );

	// Store the previous face location
	prevFaceRect = *pFaceRect;
}
Exemplo n.º 22
0
IplImage* th_plot_hist(CvHistogram* hist, int bins, const char* windowName, CvScalar lineColor) {
	th_create_image(&histImg, cvSize(512, 512 * 0.6), 8, 3);
	float xStep = histImg->width / bins;
	CvPoint p0, p1;
	cvSet(histImg, th_black, 0x0);

	float max_value = 0;
	cvGetMinMaxHistValue(hist, 0, &max_value, 0, 0);

	int i;
	for (i = 1; i < bins; i++) {
		float v0 = cvGetReal1D(hist->bins, i - 1) / max_value * histImg->height;
		float v1 = cvGetReal1D(hist->bins, i) / max_value * histImg->height;
		p0 = cvPoint((i - 1) * xStep, histImg->height - v0);
		p1 = cvPoint(i * xStep, histImg->height - v1);
		cvLine(histImg, p0, p1, lineColor, 2, 8, 0);
	}

	//cvhPutText(histImg, "hello", cvPoint(33, 33), cvScalar(0xff, 0, 0xff, 0));
	cvShowImage(windowName, histImg);
	return histImg;
}
Exemplo n.º 23
0
void BoatDetecting::startTrackObject(){
		cvInRangeS(hsv, cvScalar(0, smin, MIN(vmin, vmax), 0), cvScalar(180, 256, MAX(vmin, vmax), 0), mask);
	// 10,256,30
	
	cvSplit(hsv, hue, 0, 0, 0);
	if (!isTrackingInitialized){ // 如果跟踪窗口未初始化
		float max_val = 0.f;		
		cvSetImageROI(hue, selection);
		cvSetImageROI(mask, selection);		
		cvCalcHist(&hue, hist, 0, mask);
		cvGetMinMaxHistValue(hist, 0, &max_val, 0, 0);
		cvConvertScale(hist->bins, hist->bins, max_val ? 255. / max_val : 0., 0);
		cvResetImageROI(hue);
		cvResetImageROI(mask);
		trackWindow = selection;
		isTrackingInitialized = true;

	}

	cvCalcBackProject(&hue, backproject, hist);
	//cvShowImage("Hue Channel",backproject);
	
	cvAnd(backproject, mask, backproject, 0);
	
	//if (trackWindow.x + trackWindow.width/2< allfWidth &&trackWindow.y + trackWindow.height/2< allfHeight &&trackWindow.x>0)
	if (trackWindow.x + trackWindow.width< allfWidth &&trackWindow.y + trackWindow.height< allfHeight &&trackWindow.x>0)
		cvCamShift(backproject, trackWindow, cvTermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 20, 1), &trackComp, 0);//初始化跟踪窗口以后直接用trackWindow做跟踪,每帧都会更新
	

	//if (trackComp.rect.width<90 && trackComp.rect.y<200){
	//	trackWindow = trackComp.rect;
	//}
	//if (trackComp.rect.y>200)
	//{
	//	trackWindow = trackComp.rect;
	//}
	trackWindow = trackComp.rect;
	
}
Exemplo n.º 24
0
// ------------------------------------------------------------------------
void LABHistogram2D::Draw(IplImage* frame, int scale, CvPoint p) {
	int iscale = scale, jscale = scale;
	if (scale == 0) {
		iscale = frame->width/a_bins;
		jscale = frame->height/b_bins;
	}
	else {
		iscale = scale; jscale = scale;
	}

	float min_val = 0, max_val = 0;
	cvGetMinMaxHistValue( h, &min_val, &max_val, 0, 0 );
	for(int i=0; i<a_bins;i++ )
	{
		for(int j=0; j<b_bins;j++ )
		{
			float bin_val = cvQueryHistValue_2D( h, i, j );
			int index = (int)(NTEMPERATURES*(bin_val-min_val-1)/(max_val-min_val));
			cvRectangle( frame, cvPoint( p.x+i*iscale, p.y+j*jscale ),
						cvPoint( (i+1)*iscale - 1 + p.x, (j+1)*jscale - 1 + p.y),
						CV_RGB(HEAT_COLOR[index].R, HEAT_COLOR[index].G, HEAT_COLOR[index].B), CV_FILLED );
		}
	}
}
void CamShift::Track(IplImage *frame, CvRect &selection, bool calc_hist)
{
	int i, bin_w, c;

	cvCvtColor( frame, _hsv, CV_BGR2HSV );

	cvInRangeS( _hsv, cvScalar(0,_smin,MIN(_vmin,_vmax),0),
		cvScalar(180,256,MAX(_vmin,_vmax),0), _mask );
	cvSplit( _hsv, _hue, 0, 0, 0 );

	if(calc_hist)
	{
		float max_val = 0.f;
		cvSetImageROI( _hue, selection );
		cvSetImageROI( _mask, selection );
		cvCalcHist( &_hue, _hist, 0, _mask );
		cvGetMinMaxHistValue( _hist, 0, &max_val, 0, 0 );
		cvConvertScale( _hist->bins, _hist->bins, max_val ? 255. / max_val : 0., 0 );
		cvResetImageROI( _hue );
		cvResetImageROI( _mask );
		_track_window = selection; 
	}

	cvCalcBackProject( &_hue, _backproject, _hist );
	cvAnd( _backproject, _mask, _backproject, 0 );
	cvCamShift( _backproject, _track_window,
		cvTermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 ),
		&_track_comp, &_track_box );
	_track_window = _track_comp.rect;

	if( frame->origin )
		_track_box.angle = -_track_box.angle;

	selection = cvRect(_track_box.center.x-_track_box.size.width/2, _track_box.center.y-_track_box.size.height/2,
		selection.width, selection.height);
}
Exemplo n.º 26
0
QRect WebCamData::detectFace(const char* faceData)
{

    if (d->hasFace) {
        trackFace();
        return QRect();
    }
    if (!d->mCascade) {
        qDebug() << Q_FUNC_INFO << ": " << "Error incorrect Haar classifier cascade";
        return QRect();
    }

    CvRect* rect = 0;
    int faceSize = d->data->width / 5;
    d->mFaceSeq = cvHaarDetectObjects(d->data,
                                      d->mCascade, d->mFaceStore, 1.1, 6,
                                      CV_HAAR_DO_CANNY_PRUNING,
                                      cvSize(faceSize, faceSize));
//   qDebug() << "Number of Faces Detected" << d->mFaceSeq->total;

    if (d->mFaceSeq && d->mFaceSeq->total) {
        rect = (CvRect*) cvGetSeqElem(d->mFaceSeq, 0);
        d->hasFace = true;

        int radius = cvRound((rect->width + rect->height) * 0.25);
        CvPoint center;
        center.x = cvRound(rect->x + rect->width * 0.5);
        center.y = cvRound(rect->y + rect->height * 0.5);

        //qDebug() << "Radius : " << radius << " X: " << center.x << "Y : " << center.y;
        //histogram

        float max = 0.f;
        float range[]  = {0, 180};
        float* ranges = range;
        int bins = 30;
        d->hsvImage = cvCreateImage(cvGetSize(d->data), 8, 3);
        d->hueImage = cvCreateImage(cvGetSize(d->data), 8, 1);
        d->mask = cvCreateImage(cvGetSize(d->data), 8, 1);
        d->prob = cvCreateImage(cvGetSize(d->data), 8, 1);
        d->histogram = cvCreateHist(1, &bins, CV_HIST_ARRAY, &ranges, 1);

        updateHugeImage(d->data);

        cvSetImageROI(d->hueImage, *rect);
        cvSetImageROI(d->mask, *rect);
        cvCalcHist(&d->hueImage, d->histogram, 0, d->mask);
        cvGetMinMaxHistValue(d->histogram, 0, &max, 0, 0);
        cvConvertScale(d->histogram->bins, d->histogram->bins, max ? 255.0 / max : 0, 0);
        cvResetImageROI(d->hueImage);
        cvResetImageROI(d->mask);

        d->faceRect = *rect;

        /*
                      */
    }


    return QRect();

}
Exemplo n.º 27
0
CV_IMPL double
cvCalcGlobalOrientation( const void* orientation, const void* maskimg, const void* mhiimg,
                         double curr_mhi_timestamp, double mhi_duration )
{
    int hist_size = 12;
    cv::Ptr<CvHistogram> hist;

    CvMat  mhistub, *mhi = cvGetMat(mhiimg, &mhistub);
    CvMat  maskstub, *mask = cvGetMat(maskimg, &maskstub);
    CvMat  orientstub, *orient = cvGetMat(orientation, &orientstub);
    void*  _orient;
    float _ranges[] = { 0, 360 };
    float* ranges = _ranges;
    int base_orient;
    float shift_orient = 0, shift_weight = 0;
    float a, b, fbase_orient;
    float delbound;
    CvMat mhi_row, mask_row, orient_row;
    int x, y, mhi_rows, mhi_cols;

    if( !CV_IS_MASK_ARR( mask ))
        CV_Error( CV_StsBadMask, "" );

    if( CV_MAT_TYPE( mhi->type ) != CV_32FC1 || CV_MAT_TYPE( orient->type ) != CV_32FC1 )
        CV_Error( CV_StsUnsupportedFormat,
        "MHI and orientation must be single-channel floating-point images" );

    if( !CV_ARE_SIZES_EQ( mhi, mask ) || !CV_ARE_SIZES_EQ( orient, mhi ))
        CV_Error( CV_StsUnmatchedSizes, "" );

    if( mhi_duration <= 0 )
        CV_Error( CV_StsOutOfRange, "MHI duration must be positive" );

    if( orient->data.ptr == mhi->data.ptr )
        CV_Error( CV_StsInplaceNotSupported, "orientation image must be different from MHI" );

    // calculate histogram of different orientation values
    hist = cvCreateHist( 1, &hist_size, CV_HIST_ARRAY, &ranges );
    _orient = orient;
    cvCalcArrHist( &_orient, hist, 0, mask );

    // find the maximum index (the dominant orientation)
    cvGetMinMaxHistValue( hist, 0, 0, 0, &base_orient );
    fbase_orient = base_orient*360.f/hist_size;

    // override timestamp with the maximum value in MHI
    cvMinMaxLoc( mhi, 0, &curr_mhi_timestamp, 0, 0, mask );

    // find the shift relative to the dominant orientation as weighted sum of relative angles
    a = (float)(254. / 255. / mhi_duration);
    b = (float)(1. - curr_mhi_timestamp * a);
    delbound = (float)(curr_mhi_timestamp - mhi_duration);
    mhi_rows = mhi->rows;
    mhi_cols = mhi->cols;

    if( CV_IS_MAT_CONT( mhi->type & mask->type & orient->type ))
    {
        mhi_cols *= mhi_rows;
        mhi_rows = 1;
    }

    cvGetRow( mhi, &mhi_row, 0 );
    cvGetRow( mask, &mask_row, 0 );
    cvGetRow( orient, &orient_row, 0 );

    /*
       a = 254/(255*dt)
       b = 1 - t*a = 1 - 254*t/(255*dur) =
       (255*dt - 254*t)/(255*dt) =
       (dt - (t - dt)*254)/(255*dt);
       --------------------------------------------------------
       ax + b = 254*x/(255*dt) + (dt - (t - dt)*254)/(255*dt) =
       (254*x + dt - (t - dt)*254)/(255*dt) =
       ((x - (t - dt))*254 + dt)/(255*dt) =
       (((x - (t - dt))/dt)*254 + 1)/255 = (((x - low_time)/dt)*254 + 1)/255
     */
    for( y = 0; y < mhi_rows; y++ )
    {
        mhi_row.data.ptr = mhi->data.ptr + mhi->step*y;
        mask_row.data.ptr = mask->data.ptr + mask->step*y;
        orient_row.data.ptr = orient->data.ptr + orient->step*y;

        for( x = 0; x < mhi_cols; x++ )
            if( mask_row.data.ptr[x] != 0 && mhi_row.data.fl[x] > delbound )
            {
                /*
                   orient in 0..360, base_orient in 0..360
                   -> (rel_angle = orient - base_orient) in -360..360.
                   rel_angle is translated to -180..180
                 */
                float weight = mhi_row.data.fl[x] * a + b;
                float rel_angle = orient_row.data.fl[x] - fbase_orient;

                rel_angle += (rel_angle < -180 ? 360 : 0);
                rel_angle += (rel_angle > 180 ? -360 : 0);

                if( fabs(rel_angle) < 45 )
                {
                    shift_orient += weight * rel_angle;
                    shift_weight += weight;
                }
            }
    }

    // add the dominant orientation and the relative shift
    if( shift_weight == 0 )
        shift_weight = 0.01f;

    fbase_orient += shift_orient / shift_weight;
    fbase_orient -= (fbase_orient < 360 ? 0 : 360);
    fbase_orient += (fbase_orient >= 0 ? 0 : 360);

    return fbase_orient;
}
Exemplo n.º 28
0
// A Simple Camera Capture Framework
int main() {

	CvCapture* capture = cvCaptureFromCAM( 0 );
	if( !capture ) {
		fprintf( stderr, "ERROR: capture is NULL \n" );
		return -1;
	}

	#ifdef HALF_SIZE_CAPTURE
	cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 352/2);
	cvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 288/2);
	#endif

	// Create a window in which the captured images will be presented
	cvNamedWindow( "Source Image Window", CV_WINDOW_AUTOSIZE );
	cvNamedWindow( "Back Projected Image", CV_WINDOW_AUTOSIZE );
	cvNamedWindow( "Brightness and Contrast Window", CV_WINDOW_AUTOSIZE );
	cvNamedWindow( "Blob Output Window", CV_WINDOW_AUTOSIZE );
	cvNamedWindow( "Histogram Window", 0);

	cvNamedWindow( "Rainbow Window", CV_WINDOW_AUTOSIZE );

	// Capture one frame to get image attributes:
	source_frame = cvQueryFrame( capture );
	if( !source_frame ) {
		fprintf( stderr, "ERROR: frame is null...\n" );
		return -1;
	}

	cvCreateTrackbar("histogram\nnormalization", "Back Projected Image", &normalization_sum, 6000, NULL);
	cvCreateTrackbar("brightness", "Brightness and Contrast Window", &_brightness, 200, NULL);
	cvCreateTrackbar("contrast", "Brightness and Contrast Window", &_contrast, 200, NULL);
	cvCreateTrackbar("threshold", "Blob Output Window", &blob_extraction_threshold, 255, NULL);
	cvCreateTrackbar("min blob size", "Blob Output Window", &min_blob_size, 2000, NULL);
	cvCreateTrackbar("max blob size", "Blob Output Window", &max_blob_size, source_frame->width*source_frame->height/4, NULL);



	inputImage = cvCreateImage(cvGetSize(source_frame), IPL_DEPTH_8U, 1);
	histAdjustedImage = cvCreateImage(cvGetSize(source_frame), IPL_DEPTH_8U, 1);
	outputImage = cvCreateImage(cvGetSize(source_frame), IPL_DEPTH_8U, 3 );
	hist_image = cvCreateImage(cvSize(320,200), 8, 1);

	rainbowImage = cvCreateImage(cvGetSize(source_frame), IPL_DEPTH_8U, 3 );


	// object that will contain blobs of inputImage 
	CBlobResult blobs;
	CBlob my_enumerated_blob;

	cvInitFont(&font, CV_FONT_HERSHEY_SIMPLEX|CV_FONT_ITALIC, hScale, vScale, 0, lineWidth);





	// Some brightness/contrast stuff:
	bright_cont_image = cvCloneImage(inputImage);
	lut_mat = cvCreateMatHeader( 1, 256, CV_8UC1 );
	cvSetData( lut_mat, lut, 0 );




	while( 1 ) {

		// Get one frame
		source_frame = cvQueryFrame( capture );
		if( !source_frame ) {
			fprintf( stderr, "ERROR: frame is null...\n" );
			getchar();
			break;
		}
		cvShowImage( "Source Image Window", source_frame );
		// Do not release the frame!

		cvCvtColor(source_frame, inputImage, CV_RGB2GRAY);

		// Histogram Stuff!
		my_hist = cvCreateHist(1, hist_size_array, CV_HIST_ARRAY, ranges, 1);
		cvCalcHist( &inputImage, my_hist, 0, NULL );
		cvNormalizeHist(my_hist, normalization_sum);

		// NOTE: First argument MUST have an ampersand, or a segmentation fault will result
		cvCalcBackProject(&inputImage, histAdjustedImage, my_hist);



		// Histogram Picture
		int bin_w;
		float max_value = 0;
		cvGetMinMaxHistValue( my_hist, 0, &max_value, 0, 0 );
		cvScale( my_hist->bins, my_hist->bins, ((double)hist_image->height)/max_value, 0 );
		cvSet( hist_image, cvScalarAll(255), 0 );
		bin_w = cvRound((double)hist_image->width/hist_size);

		for(int i = 0; i < hist_size; i++ )
			cvRectangle( hist_image, cvPoint(i*bin_w, hist_image->height), cvPoint((i+1)*bin_w, hist_image->height - cvRound(cvGetReal1D(my_hist->bins,i))), cvScalarAll(0), -1, 8, 0 );
		cvShowImage( "Histogram Window", hist_image );
		cvShowImage("Back Projected Image", histAdjustedImage);






		// Brightness/contrast loop stuff:
		int brightness = _brightness - 100;
		int contrast = _contrast - 100;

		/*
		 * The algorithm is by Werner D. Streidt
		 * (http://visca.com/ffactory/archives/5-99/msg00021.html)
		 */
		if( contrast > 0 ) {
			double delta = 127.*contrast/100;
			double a = 255./(255. - delta*2);
			double b = a*(brightness - delta);
			for(int i = 0; i < 256; i++ )
			{
				int v = cvRound(a*i + b);
				if( v < 0 ) v = 0;
				if( v > 255 ) v = 255;
				lut[i] = (uchar)v;
			}
		}
		else {
			double delta = -128.*contrast/100;
			double a = (256.-delta*2)/255.;
			double b = a*brightness + delta;
			for(int i = 0; i < 256; i++ ) {
				int v = cvRound(a*i + b);
				if( v < 0 )
					v = 0;
				if( v > 255 )
					v = 255;
				lut[i] = (uchar)v;
			}
		}

		cvLUT( inputImage, bright_cont_image, lut_mat );
		cvShowImage( "Brightness and Contrast Window", bright_cont_image);







		// ---------------
		// Blob Manipulation Code begins here:

		// Extract the blobs using a threshold of 100 in the image
		blobs = CBlobResult( bright_cont_image, NULL, blob_extraction_threshold, true );

		// discard the blobs with less area than 5000 pixels
		// ( the criteria to filter can be any class derived from COperadorBlob ) 
		blobs.Filter( blobs, B_INCLUDE, CBlobGetArea(), B_GREATER_OR_EQUAL, min_blob_size);
		blobs.Filter( blobs, B_EXCLUDE, CBlobGetArea(), B_GREATER, max_blob_size);

		// build an output image equal to the input but with 3 channels (to draw the coloured blobs)
		cvMerge( bright_cont_image, bright_cont_image, bright_cont_image, NULL, outputImage );

		// plot the selected blobs in a output image
		for (int i=0; i < blobs.GetNumBlobs(); i++) {
			blobs.GetNthBlob( CBlobGetArea(), i, my_enumerated_blob );
			// Color 5/6 of the color wheel (300 degrees)
			my_enumerated_blob.FillBlob( outputImage, cv_hsv2rgb((float)i/blobs.GetNumBlobs() * 300, 1, 1));
		}
		// END Blob Manipulation Code
		// ---------------


		sprintf(str, "Count: %d", blobs.GetNumBlobs());
		cvPutText(outputImage, str, cvPoint(50, 25), &font, cvScalar(255,0,255));
		
		cvShowImage("Blob Output Window", outputImage);






/*
		// Rainbow manipulation:
		for (int i=0; i < CV_CAP_PROP_FRAME_WIDTH; i++) {
			for (int j=0; j < CV_CAP_PROP_FRAME_HEIGHT; j++) {
// This line is not figure out yet...
//				pixel_color_set = ((uchar*)(rainbowImage->imageData + rainbowImage->widthStep * j))[i * 3]

				((uchar*)(rainbowImage->imageData + rainbowImage->widthStep * j))[i * 3] = 30;
				((uchar*)(rainbowImage->imageData + rainbowImage->widthStep * j))[i * 3 + 1] = 30;
				((uchar*)(rainbowImage->imageData + rainbowImage->widthStep * j))[i * 3 + 2] = 30;
			}
		}
		cvShowImage("Rainbow Window", rainbowImage);
*/







		//If ESC key pressed, Key=0x10001B under OpenCV 0.9.7(linux version),
		//remove higher bits using AND operator
		if( (cvWaitKey(10) & 255) == 27 ) break;

	}

	cvReleaseImage(&inputImage);
	cvReleaseImage(&histAdjustedImage);
	cvReleaseImage(&hist_image);
	cvReleaseImage(&bright_cont_image);
	cvReleaseImage(&outputImage);
	cvReleaseImage(&rainbowImage);

	// Release the capture device housekeeping
	cvReleaseCapture( &capture );
	cvDestroyAllWindows();

	return 0;
}
Exemplo n.º 29
0
//=========================================
CvRect camKalTrack(IplImage* frame, camshift_kalman_tracker& camKalTrk) {
//=========================================
	if (!frame)
		printf("Input frame empty!\n");

	cvCopy(frame, camKalTrk.image, 0);
	cvCvtColor(camKalTrk.image, camKalTrk.hsv, CV_BGR2HSV); // BGR to HSV

	if (camKalTrk.trackObject) {
		int _vmin = vmin, _vmax = vmax;
		cvInRangeS(camKalTrk.hsv, cvScalar(0, smin, MIN(_vmin,_vmax), 0), cvScalar(180, 256, MAX(_vmin,_vmax), 0), camKalTrk.mask); // MASK
		cvSplit(camKalTrk.hsv, camKalTrk.hue, 0, 0, 0); //  HUE
		if (camKalTrk.trackObject < 0) {
			float max_val = 0.f;
			boundaryCheck(camKalTrk.originBox, frame->width, frame->height);
			cvSetImageROI(camKalTrk.hue, camKalTrk.originBox); // for ROI
			cvSetImageROI(camKalTrk.mask, camKalTrk.originBox); // for camKalTrk.mask
			cvCalcHist(&camKalTrk.hue, camKalTrk.hist, 0, camKalTrk.mask); //
			cvGetMinMaxHistValue(camKalTrk.hist, 0, &max_val, 0, 0);
			cvConvertScale(camKalTrk.hist->bins, camKalTrk.hist->bins, max_val ? 255. / max_val : 0., 0); //  bin  [0,255]
			cvResetImageROI(camKalTrk.hue); // remove ROI
			cvResetImageROI(camKalTrk.mask);
			camKalTrk.trackWindow = camKalTrk.originBox;
			camKalTrk.trackObject = 1;
			camKalTrk.lastpoint = camKalTrk.predictpoint = cvPoint(camKalTrk.trackWindow.x + camKalTrk.trackWindow.width / 2,
					camKalTrk.trackWindow.y + camKalTrk.trackWindow.height / 2);
			getCurrState(camKalTrk.kalman, camKalTrk.lastpoint, camKalTrk.predictpoint);//input curent state
		}
		//(x,y,vx,vy),
		camKalTrk.prediction = cvKalmanPredict(camKalTrk.kalman, 0);//predicton=kalman->state_post

		camKalTrk.predictpoint = cvPoint(cvRound(camKalTrk.prediction->data.fl[0]), cvRound(camKalTrk.prediction->data.fl[1]));

		camKalTrk.trackWindow = cvRect(camKalTrk.predictpoint.x - camKalTrk.trackWindow.width / 2, camKalTrk.predictpoint.y
				- camKalTrk.trackWindow.height / 2, camKalTrk.trackWindow.width, camKalTrk.trackWindow.height);

		camKalTrk.trackWindow = checkRectBoundary(cvRect(0, 0, frame->width, frame->height), camKalTrk.trackWindow);

		camKalTrk.searchWindow = cvRect(camKalTrk.trackWindow.x - region, camKalTrk.trackWindow.y - region, camKalTrk.trackWindow.width + 2
				* region, camKalTrk.trackWindow.height + 2 * region);

		camKalTrk.searchWindow = checkRectBoundary(cvRect(0, 0, frame->width, frame->height), camKalTrk.searchWindow);

		cvSetImageROI(camKalTrk.hue, camKalTrk.searchWindow);
		cvSetImageROI(camKalTrk.mask, camKalTrk.searchWindow);
		cvSetImageROI(camKalTrk.backproject, camKalTrk.searchWindow);

		cvCalcBackProject( &camKalTrk.hue, camKalTrk.backproject, camKalTrk.hist ); // back project

		cvAnd(camKalTrk.backproject, camKalTrk.mask, camKalTrk.backproject, 0);

		camKalTrk.trackWindow = cvRect(region, region, camKalTrk.trackWindow.width, camKalTrk.trackWindow.height);

		if (camKalTrk.trackWindow.height > 5 && camKalTrk.trackWindow.width > 5) {
			// calling CAMSHIFT
			cvCamShift(camKalTrk.backproject, camKalTrk.trackWindow, cvTermCriteria(CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1),
					&camKalTrk.trackComp, &camKalTrk.trackBox);

			/*cvMeanShift( camKalTrk.backproject, camKalTrk.trackWindow,
			 cvTermCriteria( CV_TERMCRIT_EPS | CV_TERMCRIT_ITER, 10, 1 ),
			 &camKalTrk.trackComp);*/
		}
		else {
			camKalTrk.trackComp.rect.x = 0;
			camKalTrk.trackComp.rect.y = 0;
			camKalTrk.trackComp.rect.width = 0;
			camKalTrk.trackComp.rect.height = 0;
		}

		cvResetImageROI(camKalTrk.hue);
		cvResetImageROI(camKalTrk.mask);
		cvResetImageROI(camKalTrk.backproject);
		camKalTrk.trackWindow = camKalTrk.trackComp.rect;
		camKalTrk.trackWindow = cvRect(camKalTrk.trackWindow.x + camKalTrk.searchWindow.x, camKalTrk.trackWindow.y
				+ camKalTrk.searchWindow.y, camKalTrk.trackWindow.width, camKalTrk.trackWindow.height);

		camKalTrk.measurepoint = cvPoint(camKalTrk.trackWindow.x + camKalTrk.trackWindow.width / 2, camKalTrk.trackWindow.y
				+ camKalTrk.trackWindow.height / 2);
		camKalTrk.realposition->data.fl[0] = camKalTrk.measurepoint.x;
		camKalTrk.realposition->data.fl[1] = camKalTrk.measurepoint.y;
		camKalTrk.realposition->data.fl[2] = camKalTrk.measurepoint.x - camKalTrk.lastpoint.x;
		camKalTrk.realposition->data.fl[3] = camKalTrk.measurepoint.y - camKalTrk.lastpoint.y;
		camKalTrk.lastpoint = camKalTrk.measurepoint;//keep the current real position

		//measurement x,y
		cvMatMulAdd( camKalTrk.kalman->measurement_matrix/*2x4*/, camKalTrk.realposition/*4x1*/,/*measurementstate*/0, camKalTrk.measurement );
		cvKalmanCorrect(camKalTrk.kalman, camKalTrk.measurement);

		cvRectangle(frame, cvPoint(camKalTrk.trackWindow.x, camKalTrk.trackWindow.y), cvPoint(camKalTrk.trackWindow.x
				+ camKalTrk.trackWindow.width, camKalTrk.trackWindow.y + camKalTrk.trackWindow.height), CV_RGB(255,128,0), 4, 8, 0);
	}
	// set new selection if it exists
	if (camKalTrk.selectObject && camKalTrk.selection.width > 0 && camKalTrk.selection.height > 0) {
		cvSetImageROI(camKalTrk.image, camKalTrk.selection);
		cvXorS(camKalTrk.image, cvScalarAll(255), camKalTrk.image, 0);
		cvResetImageROI(camKalTrk.image);
	}

	return camKalTrk.trackWindow;
}
Exemplo n.º 30
0
int main( int argc, char** argv ) {

    IplImage* src;

    if( argc == 2 && (src=cvLoadImage(argv[1], 1))!= 0) {

        // Compute the HSV image, and decompose it into separate planes.
        //
        IplImage* hsv = cvCreateImage( cvGetSize(src), 8, 3 ); 
        cvCvtColor( src, hsv, CV_BGR2HSV );

        IplImage* h_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
        IplImage* s_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
        IplImage* v_plane  = cvCreateImage( cvGetSize(src), 8, 1 );
        IplImage* planes[] = { h_plane, s_plane };
        cvCvtPixToPlane( hsv, h_plane, s_plane, v_plane, 0 );

        // Build the histogram and compute its contents.
        //
        int h_bins = 30, s_bins = 32; 
        CvHistogram* hist;
        {
          int    hist_size[] = { h_bins, s_bins };
          float  h_ranges[]  = { 0, 180 };          // hue is [0,180]
          float  s_ranges[]  = { 0, 255 }; 
          float* ranges[]    = { h_ranges, s_ranges };
          hist = cvCreateHist( 
            2, 
            hist_size, 
            CV_HIST_ARRAY, 
            ranges, 
            1 
          ); 
        }
        cvCalcHist( planes, hist, 0, 0 );

        // Create an image to use to visualize our histogram.
        //
        int scale = 10;
        IplImage* hist_img = cvCreateImage(  
          cvSize( h_bins * scale, s_bins * scale ), 
          8, 
          3
        ); 
        cvZero( hist_img );

        // populate our visualization with little gray squares.
        //
        float max_value = 0;
        cvGetMinMaxHistValue( hist, 0, &max_value, 0, 0 );

        for( int h = 0; h < h_bins; h++ ) {
            for( int s = 0; s < s_bins; s++ ) {
                float bin_val = cvQueryHistValue_2D( hist, h, s );
                int intensity = cvRound( bin_val * 255 / max_value );
                cvRectangle( 
                  hist_img, 
                  cvPoint( h*scale, s*scale ),
                  cvPoint( (h+1)*scale - 1, (s+1)*scale - 1),
                  CV_RGB(intensity,intensity,intensity), 
                  CV_FILLED
                );
            }
        }

        cvNamedWindow( "Source", 1 );
        cvShowImage(   "Source", src );

        cvNamedWindow( "H-S Histogram", 1 );
        cvShowImage(   "H-S Histogram", hist_img );

        cvWaitKey(0);
    }
}