Beispiel #1
0
void asef_destroy(AsefEyeLocator *asef){

	cvReleaseMemStorage( &asef->face_detection_buffer );
	cvReleaseHaarClassifierCascade( &asef->face_detection_classifier );

	cvReleaseMat(&asef->lfilter);
	cvReleaseMat(&asef->rfilter);
	cvReleaseMat(&asef->lfilter_dft);
	cvReleaseMat(&asef->rfilter_dft);
	cvReleaseMat(&asef->scaled_face_image_32fc1);
	cvReleaseMat(&asef->scaled_face_image_8uc1);
	cvReleaseMat(&asef->lcorr);
	cvReleaseMat(&asef->rcorr);
	cvReleaseMat(&asef->lroi);
	cvReleaseMat(&asef->rroi);
	cvReleaseMat(&asef->lut);
}
Beispiel #2
0
void CvGBTrees::clear()
{
    if( weak )
    {
        CvSeqReader reader;
        CvSlice slice = CV_WHOLE_SEQ;
        CvDTree* tree;

        //data->shared = false;
        for (int i=0; i<class_count; ++i)
        {
            int weak_count = cvSliceLength( slice, weak[i] );
            if ((weak[i]) && (weak_count))
            {
                cvStartReadSeq( weak[i], &reader );
                cvSetSeqReaderPos( &reader, slice.start_index );
                for (int j=0; j<weak_count; ++j)
                {
                    CV_READ_SEQ_ELEM( tree, reader );
                    //tree->clear();
                    delete tree;
                    tree = 0;
                }
            }
        }
        for (int i=0; i<class_count; ++i)
            if (weak[i]) cvReleaseMemStorage( &(weak[i]->storage) );
        delete[] weak;
    }
    if (data)
    {
        data->shared = false;
        delete data;
    }
    weak = 0;
    data = 0;
    delta = 0.0f;
    cvReleaseMat( &orig_response );
    cvReleaseMat( &sum_response );
    cvReleaseMat( &sum_response_tmp );
    cvReleaseMat( &subsample_train );
    cvReleaseMat( &subsample_test );
    cvReleaseMat( &sample_idx );
    cvReleaseMat( &missing );
    cvReleaseMat( &class_labels );
}
Beispiel #3
0
CvSeq*cvSegmentFGMask(CvArr* _mask, int poly1Hull0, float perimScale, CvMemStorage* storage, CvPoint offset)
{
	CvMat mstub, *mask = cvGetMat(_mask, &mstub);
	CvMemStorage* tempStorage = storage ? storage : cvCreateMemStorage();
	CvSeq *contours, *c;
	int nContours = 0;
	CvContourScanner scanner;

	// clean up raw mask
	cvMorphologyEx(mask, mask, 0, 0, CV_MOP_OPEN, 1);
	cvMorphologyEx(mask, mask, 0, 0, CV_MOP_CLOSE, 1);
	// find contours around only bigger regions
	scanner = cvStartFindContours(mask, tempStorage,
		sizeof(CvContour), CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE, offset);

	while ((c = cvFindNextContour(scanner)) != 0)
	{
		double len = cvContourPerimeter(c);
		double q = (mask->rows + mask->cols) / perimScale; // calculate perimeter len threshold
		if (len < q) //Get rid of blob if it's perimeter is too small
			cvSubstituteContour(scanner, 0);
		else //Smooth it's edges if it's large enough
		{
			CvSeq* newC;
			if (poly1Hull0) //Polygonal approximation of the segmentation 
				newC = cvApproxPoly(c, sizeof(CvContour), tempStorage, CV_POLY_APPROX_DP, 2, 0);
			else //Convex Hull of the segmentation
				newC = cvConvexHull2(c, tempStorage, CV_CLOCKWISE, 1);
			cvSubstituteContour(scanner, newC);
			nContours++;
		}
	}
	contours = cvEndFindContours(&scanner);
	// paint the found regions back into the image
	cvZero(mask);
	for (c = contours; c != 0; c = c->h_next)
		cvDrawContours(mask, c, cvScalarAll(255), cvScalarAll(0), -1, CV_FILLED, 8,
		cvPoint(-offset.x, -offset.y));
	if (tempStorage != storage)
	{
		cvReleaseMemStorage(&tempStorage);
		contours = 0;
	}
	return contours;
}
/*!
    \fn CvGaborFeature::writeXML(const char* filename) const
 */
void CvGaborFeature::writeXML(const char* filename) const
{
  CvMemStorage* storage = cvCreateMemStorage( 0 );
  CvFileStorage* fs = cvOpenFileStorage( filename, storage, CV_STORAGE_WRITE);
 
  cvStartWriteStruct( fs, "CvGaborFeature",
                      CV_NODE_MAP, NULL,
                      cvAttrList(0,0));
  cvWriteInt(fs, "x", getx());
  cvWriteInt(fs, "y", gety());
  cvWriteInt(fs, "Mu",getMu());
  cvWriteInt(fs, "Nu",getNu());
  cvEndWriteStruct(fs); 
  cvEndWriteStruct( fs );
  
  cvReleaseFileStorage(&fs);
  cvReleaseMemStorage(&storage);
}
Beispiel #5
0
CvSeq* HoughCircle::locateHoughCircles(IplImage* img,double min_distance, double upperThreshold, double accumulatorThreshold, double min_radius, double max_radius ){
	//IplImage* gray = cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
	//storage = cvCreateMemStorage(0);

    IplImage* gray=cvCreateImage(cvGetSize(img), IPL_DEPTH_8U, 1);
    CvMemStorage* storage = cvCreateMemStorage(0);
    cvCvtColor( img, gray, CV_BGR2GRAY );

   // cvShowImage("Gray",gray);
   // cvEqualizeHist(gray,gray);
   // cvShowImage("Hist Eq Gray",gray);

	CvSeq* circle = cvHoughCircles( gray, storage, CV_HOUGH_GRADIENT, 2, min_distance, upperThreshold, accumulatorThreshold, min_radius, max_radius);
	cvReleaseImage(&gray);
	cvReleaseMemStorage(&storage);

	return circle;
}
/* Clean up */
static void
gst_face_blur_finalize (GObject * obj)
{
  GstFaceBlur *filter = GST_FACE_BLUR (obj);

  if (filter->cvGray)
    cvReleaseImage (&filter->cvGray);

  if (filter->cvStorage)
    cvReleaseMemStorage (&filter->cvStorage);

  if (filter->cvCascade)
    cvReleaseHaarClassifierCascade (&filter->cvCascade);

  g_free (filter->profile);

  G_OBJECT_CLASS (gst_face_blur_parent_class)->finalize (obj);
}
Beispiel #7
0
CHandDrawEffect::~CHandDrawEffect()
{
	for(int i = 0; i < PATT_NUM; i++) {
		if(hatching[i])
			cvReleaseImage(&hatching[i]);
	}

	if(hsv)			cvReleaseImage(&hsv);
	if(grayImage)	cvReleaseImage(&grayImage);
	if(binaryImage)	cvReleaseImage(&binaryImage);
	if(imageA)		cvReleaseImage(&imageA);
	if(imageB)		cvReleaseImage(&imageB);
	if(imageC)		cvReleaseImage(&imageC);
	if(imageD)		cvReleaseImage(&imageD);
	if(imageE)		cvReleaseImage(&imageE);
	if(scanningLine) cvReleaseImage(&scanningLine);
	if(memStorage0)	cvReleaseMemStorage(&memStorage0);
}
Beispiel #8
0
void moBlobFinderModule::applyFilter(IplImage *src) {
	this->storage = cvCreateMemStorage(0);
	this->clearBlobs();
	this->storage = cvCreateMemStorage(0);
	cvCopy(src, this->output_buffer);
	
        CvSeq *contours = 0;
	cvFindContours(this->output_buffer, this->storage, &contours, sizeof(CvContour), CV_RETR_CCOMP);

        cvDrawContours(this->output_buffer, contours, cvScalarAll(255), cvScalarAll(255), 100);

	// Consider each contour a blob and extract the blob infos from it.
	int size;
	int ratio;
	int min_size = this->property("min_size").asInteger();
	int max_size = this->property("max_size").asInteger();
	CvSeq *cur_cont = contours;
	while (cur_cont != 0) {
		CvRect rect	= cvBoundingRect(cur_cont, 0);
		size = rect.width * rect.height;

		// Check ratio to make sure blob can physically represent a finger
		// magic number 6 is used for now to represent maximum ratio of
		// Length/thickness of finger
		if (rect.width < rect.height) {
			ratio = rect.height / (double)rect.width;
		} else {
			ratio = rect.width / (double)rect.height;
		}
		if ((ratio <= 6) && (size >= min_size) && (size <= max_size)) {
			moDataGenericContainer *blob = new moDataGenericContainer();
			blob->properties["implements"] = new moProperty("pos,size");
			blob->properties["x"] = new moProperty((rect.x + rect.width / 2) / (double) src->width);
			blob->properties["y"] = new moProperty((rect.y + rect.height / 2) / (double) src->height);
			blob->properties["width"] = new moProperty(rect.width);
			blob->properties["height"] = new moProperty(rect.height);
			this->blobs->push_back(blob);
			cvRectangle(this->output_buffer, cvPoint(rect.x,rect.y), cvPoint(rect.x + rect.width,rect.x + rect.height), cvScalar(250,10,10), 1);
		}
		cur_cont = cur_cont->h_next;
	}
	cvReleaseMemStorage(&this->storage);
    this->output_data->push(this->blobs);
}
Beispiel #9
0
// Perform face detection on the input image, using the given Haar Cascade. 
// Returns a rectangle for the detected region in the given image.
CvRect detectFaceInImage(IplImage* inputImg, CvHaarClassifierCascade* cascade, CvSize faceSize)
{
	// Only search for 1 face.
	int flags = CV_HAAR_FIND_BIGGEST_OBJECT | CV_HAAR_DO_ROUGH_SEARCH;
	// How detailed should the search be.
	float search_scale_factor = 1.1f;
	IplImage *detectImg = NULL;
	IplImage *greyImg = NULL;
	CvMemStorage* storage = NULL;

	CvSeq* rects = NULL;
	CvSize srcSize;
	CvRect rc;
	int nFaces;

	storage = cvCreateMemStorage(0); // Allocate 64KB memory space
	cvClearMemStorage(storage);

	// If the image is color, use a greyscale copy of the image.
	detectImg = (IplImage*)inputImg;
	if (inputImg->nChannels > 1) {
		srcSize = cvSize(inputImg->width, inputImg->height);
		greyImg = cvCreateImage(srcSize, IPL_DEPTH_8U, 1);
		cvCvtColor(inputImg, greyImg, CV_BGR2GRAY);
		detectImg = greyImg;	// Use the greyscale image.
	}

	// Detect all the faces in the greyscale image.
	rects = cvHaarDetectObjects(detectImg, cascade, storage,
			search_scale_factor, 3, flags, faceSize);
	nFaces = rects->total;

	// Get the first detected face (the biggest).
	if (nFaces > 0)
		rc = *(CvRect*)cvGetSeqElem(rects, 0);
	else
		rc = cvRect(-1, -1, -1, -1);	// Couldn't find the face.

	if (greyImg != NULL)
		cvReleaseImage(&greyImg);
	cvReleaseMemStorage(&storage);

	return rc;	// Return the biggest face found, or (-1,-1,-1,-1).
}
Beispiel #10
0
int main()
{
	const int imgHeight = 500;
	const int imgWidth = 500;

	IplImage* pImgSrc = cvCreateImage(cvSize(imgWidth, imgHeight), IPL_DEPTH_8U, 1); // ԭʼͼ
	IplImage* pImgContour = NULL; // ÂÖÀªÍ¼

	CvMemStorage* pMemStorage = cvCreateMemStorage(0); // ÁÙʱ´æ´¢Çø
	CvSeq* pContour = 0; // ´æ´¢ÂÖÀªµã

	// »æÖÆԭʼͼƬ
	DrawImage(pImgSrc);

	// ÏÔʾԭʼͼ
	cvNamedWindow("Source", CV_WINDOW_AUTOSIZE);
	cvShowImage("Source", pImgSrc);

	// ΪÂÖÀªÍ¼ÉêÇë¿Õ¼ä, 3ͨµÀͼÏñ
	pImgContour = cvCreateImage(cvGetSize(pImgSrc), IPL_DEPTH_8U, 3);

	// ½«µ¥Í¨µÀ»Ò¶Èͼת»¯Îª3ͨµÀ»Ò¶Èͼ
	//cvCvtColor(pImgSrc, pImgContour, CV_GRAY2BGR);
	cvZero(pImgContour);

	// ²éÕÒÂÖÀª
	cvFindContours(pImgSrc, pMemStorage, &pContour, sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0, 0));

	// ½«ÂÖÀª»­³ö
	cvDrawContours(pImgContour, pContour, CV_RGB(0, 0, 255), CV_RGB(255, 0, 0), 2, 2, 8, cvPoint(0, 0));

	// ÏÔʾÂÖÀªÍ¼
	cvNamedWindow("Contour", CV_WINDOW_AUTOSIZE);
	cvShowImage("Contour", pImgContour);

	cvWaitKey(0);

	cvDestroyWindow("Contour");
	cvDestroyWindow("Source");
	cvReleaseImage(&pImgSrc);
	cvReleaseImage(&pImgContour);
	cvReleaseMemStorage(&pMemStorage);
	return 0;
}
FindObjectMain::~FindObjectMain()
{
// This releases all the arrays
	if(storage) cvReleaseMemStorage(&storage);
	if(object_image) cvReleaseImage(&object_image);
	if(scene_image) cvReleaseImage(&scene_image);
	if(prev_object) delete [] prev_object;
	delete affine;
	delete temp;
	delete overlayer;
	
    if(blob_param.pBT) cvReleaseBlobTracker(&blob_param.pBT);
    if(blob_param.pBD) cvReleaseBlobDetector(&blob_param.pBD);
    if(blob_param.pBTGen) cvReleaseBlobTrackGen(&blob_param.pBTGen);
    if(blob_param.pBTA) cvReleaseBlobTrackAnalysis(&blob_param.pBTA);
    if(blob_param.pFG) cvReleaseFGDetector(&blob_param.pFG);
    if(blob_pTracker) cvReleaseBlobTrackerAuto(&blob_pTracker);
	
}
void catcierge_haar_matcher_destroy(catcierge_matcher_t **octx)
{
	catcierge_haar_matcher_t *ctx;

	if (!octx || !(*octx))
		return;

	ctx = (catcierge_haar_matcher_t *)*octx;

	if (ctx->cascade)
	{
		cv2CascadeClassifier_destroy(ctx->cascade);
		ctx->cascade = NULL;
	}

	if (ctx->kernel2x2)
	{
		cvReleaseStructuringElement(&ctx->kernel2x2);
		ctx->kernel2x2 = NULL;
	}

	if (ctx->kernel3x3)
	{
		cvReleaseStructuringElement(&ctx->kernel3x3);
		ctx->kernel3x3 = NULL;
	}

	if (ctx->kernel5x1)
	{
		cvReleaseStructuringElement(&ctx->kernel5x1);
		ctx->kernel5x1 = NULL;
	}

	if (ctx->storage)
	{
		cvReleaseMemStorage(&ctx->storage);
		ctx->storage = NULL;
	}

	free(ctx);
	*octx = NULL;
}
Beispiel #13
0
/* 
 * Prints a contour on a dst Image. Used for debugging.
 * prints text at the side of a contour.
 * depthLevel sets the level in the contour tree(to include/exclue holes)
 */
void Contours::printContour(int depthLevel, CvScalar color,IplImage * dst){
	
	CvFont font;
	int line_type=CV_AA;
	
	char * a=(char *) malloc(20);
	char * b=(char *) malloc(20);
	char * c=(char *) malloc(20);
	char * d=(char *) malloc(20);
	char * e=(char *) malloc(20);
	
	
	cvDrawContours( dst, this->c, CV_RGB(255,0,0), CV_RGB(0,255,0), 
		depthLevel, 3, CV_AA, cvPoint(0,0) );
	
	CvMemStorage* mem = cvCreateMemStorage(0);
	CvBox2D box=cvMinAreaRect2(this->c,mem);
	
	
	//~ traversePoints(this->c);

	std::vector<int> centroid=this->getCentroid();
	CvPoint pt2=cvPoint(centroid[0]+5,centroid[1]+5);
	CvPoint pt3=cvPoint(centroid[0]+5,centroid[1]+15);
	CvPoint pt4=cvPoint(centroid[0]+5,centroid[1]+25);
	CvPoint pt5=cvPoint(centroid[0]+5,centroid[1]+35);
	CvPoint pt6=cvPoint(centroid[0]+5,centroid[1]+45);
	sprintf(a,"per: %g",this->getPerimeter());
	sprintf(b,"zone: %d",getPointZone(this->x,this->y));
	sprintf(c,"area: %g",this->getArea());
	sprintf(d,"ecc: %g",this->getPerimeter()*this->getPerimeter()/this->getArea());
	//~ sprintf(d,"boxArea: %g",(double) this->getArea()/(box.size.width*box.size.height));
	
	cvInitFont( &font, CV_FONT_HERSHEY_COMPLEX, 0.5, 0.5, 0.0,0.5, line_type );
	cvPutText( dst, a, pt2, &font, CV_RGB(255,255,0));
	cvPutText( dst, c, pt3, &font, CV_RGB(255,255,0));
	cvPutText( dst, b, pt4, &font, CV_RGB(255,255,0));
	cvPutText( dst, d, pt5, &font, CV_RGB(255,255,0));

	//~ free(a);
	cvReleaseMemStorage(&mem);
}
Beispiel #14
0
CV_IMPL void
icvStartScanGraph( CvGraph* graph, CvGraphScanner* scanner,
                   CvGraphVtx* vtx, int mask )
{
    CvMemStorage* child_storage = 0;

    CV_FUNCNAME("icvStartScanGraph");

    __BEGIN__;

    if( !graph || !scanner )
        CV_ERROR_FROM_STATUS( CV_NULLPTR_ERR );

    if( !(graph->storage ))
        CV_ERROR_FROM_STATUS( CV_NULLPTR_ERR );

    memset( scanner, 0, sizeof(*scanner));

    scanner->graph = graph;
    scanner->mask = mask;
    scanner->vtx = vtx;
    scanner->index = vtx == 0 ? 0 : -1;

    CV_CALL( child_storage = cvCreateChildMemStorage( graph->storage ));

    CV_CALL( scanner->stack = cvCreateSeq( 0, sizeof(CvSet),
                       sizeof(CvGraphItem), child_storage ));

    CV_CALL( icvSeqElemsClearMask( (CvSeq*)graph,
                                   CV_FIELD_OFFSET( flags, CvGraphVtx ),
                                   CV_GRAPH_ITEM_VISITED_FLAG|
                                   CV_GRAPH_SEARCH_TREE_NODE_FLAG ));

    CV_CALL( icvSeqElemsClearMask( (CvSeq*)(graph->edges),
                                   CV_FIELD_OFFSET( flags, CvGraphEdge ),
                                   CV_GRAPH_ITEM_VISITED_FLAG ));

    __END__;

    if( cvGetErrStatus() < 0 )
        cvReleaseMemStorage( &child_storage );
}
Beispiel #15
0
int main( int argc, char** argv )
{
	CvCapture *capture;
	IplImage  *frame;
	int       key;
	
	//NamNguyen comment and add(2lines below)
	//char      *filename = "haarcascade_frontalface_alt.xml";	
	char filename[] = "haarcascade_frontalface_alt.xml";


	cascade = ( CvHaarClassifierCascade* )cvLoad( filename, 0, 0, 0 );
	storage = cvCreateMemStorage( 0 );
	capture = cvCaptureFromCAM( 0 );

	assert( cascade && storage && capture );

	cvNamedWindow( "video", 1 );

	while( key != 'q' ) {
		frame = cvQueryFrame( capture );

		if( !frame ) {
			fprintf( stderr, "Cannot query frame!\n" );
			break;
		}

		cvFlip( frame, frame, -1 );
		frame->origin = 0;

		detectFaces( frame );

		key = cvWaitKey( 10 );
	}

	cvReleaseCapture( &capture );
	cvDestroyWindow( "video" );
	cvReleaseHaarClassifierCascade( &cascade );
	cvReleaseMemStorage( &storage );

	return 0;
}
Beispiel #16
0
/* boxArea filter - checks that the area of a contour
 * is at least minAreaRatio of that of the contour bounding box*/
int Contours::boxAreaFilter(double minAreaRatio){
	CvBox2D box;
	CvMemStorage* mem = cvCreateMemStorage(0);
	double boxArea,contourArea,dif,ret;
	
	box=cvMinAreaRect2(this->c,mem);
	boxArea=box.size.width*box.size.height;
	contourArea=this->getArea();
	dif=boxArea-contourArea;
	ret=(1- (dif/boxArea));
	
	/* Use this to set it by zone
	int zone=getPointZone(this->x,this->y);
	double minAreaRatioByZone[]={0,0.6,0.55,0.55,0.55};
    return ret > minAreaRatioByZone[zone];
    */
    cvReleaseMemStorage( &mem );
	
	return ret > minAreaRatio;
	}
Beispiel #17
0
/* rectangular aspect filter - checks that a contour bounding rectangle
 * has certain width/height proportions */
int Contours::rectangularAspectFilter(double minWidthHeightRatio, double maxWidthHeightRatio ){
	CvBox2D box;
	CvMemStorage* mem = cvCreateMemStorage(0);
	int ret;
	
	box=cvMinAreaRect2(this->c,mem);
	
	if( (box.size.width > minWidthHeightRatio* box.size.height) &&
	 (box.size.width < (maxWidthHeightRatio)* box.size.height) || 
	 (box.size.height > minWidthHeightRatio* box.size.width) &&
     (box.size.height < (maxWidthHeightRatio)*box.size.width)){
		  ret=1;
	 }
	 else{
		ret=0;	
	}
	 
	 cvReleaseMemStorage( &mem );
	 return ret;
}
static void
kms_face_detector_finalize (GObject * object)
{
    KmsFaceDetector *facedetector = KMS_FACE_DETECTOR (object);

    cvReleaseImageHeader (&facedetector->priv->cvImage);
    cvReleaseImage (&facedetector->priv->cvResizedImage);

    if (facedetector->priv->pStorageFace != NULL)
        cvClearMemStorage (facedetector->priv->pStorageFace);
    if (facedetector->priv->pFaceRectSeq != NULL)
        cvClearSeq (facedetector->priv->pFaceRectSeq);

    cvReleaseMemStorage (&facedetector->priv->pStorageFace);
    cvReleaseHaarClassifierCascade (&facedetector->priv->pCascadeFace);

    g_mutex_clear (&facedetector->priv->mutex);

    G_OBJECT_CLASS (kms_face_detector_parent_class)->finalize (object);
}
IplImage* BouyBaseObject::SegmentationMask(const IplImage * imgIn) const
{
    IplImage * imgOut = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);
    IplImage * src = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);
    IplImage* hsv = cvCreateImage( cvGetSize(imgIn), 8, 3 );

    IplImage * chan0 = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);
    IplImage * chan1 = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);
    IplImage * chan2 = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);
    IplImage * chan3 = cvCreateImage(cvGetSize(imgIn),IPL_DEPTH_8U, 1);

    cvCvtColor( imgIn, hsv, CV_BGR2YCrCb );
    cvSplit(hsv,chan0,chan1,chan2, NULL);

    //cvConvertImage(imgIn,src);

    src = cvCloneImage(chan0);
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* comp = NULL;
    //lower last param for more segments
    cvPyrSegmentation( src, imgOut, storage, &comp, 3, 200, 50 );
    cvAbsDiffS(imgOut,imgOut,CV_RGB(255,255,255));
    //cvNormalize(imgOut,imgOut,255,0, CV_MINMAX);
    //cvThreshold(imgOut,imgOut,250,255,CV_THRESH_TOZERO);
//        int n_comp = comp->total;
//        for( int i=0; i<n_comp; i++ )
//        {
//            CvConnectedComp* cc = (CvConnectedComp*) cvGetSeqElem( comp, i );
//            cvDrawRect(imgOut,cvPoint(cc->rect.x,cc->rect.y),cvPoint(cc->rect.x+cc->rect.width,cc->rect.y+cc->rect.height),CV_RGB(255,255,255));

//        //do_something_with( cc );
//        }
    cvReleaseImage(&src);
    cvReleaseImage(&hsv);
    cvReleaseImage(&chan0);
    cvReleaseImage(&chan1);
    cvReleaseImage(&chan2);
    cvReleaseImage(&chan3);
    cvReleaseMemStorage( &storage );
    return imgOut;
}
vector<VisionRecognitionResult> KitechSurfObjectRecognitionComp::Recognize(vector<unsigned char> image,int width,int height,int pixelBytes)
{
	vector<VisionRecognitionResult> _recognitionResult(0);

	IplImage *cvImage = cvCreateImageHeader( cvSize(width, height), 8, pixelBytes );
	cvImage->imageData = (char *)&image[0];

	IplImage *grayImage = cvCreateImage( cvGetSize(cvImage), 8, 1 );
	cvCvtColor( cvImage, grayImage, CV_BGR2GRAY );

    CvMemStorage *imageStorage = cvCreateMemStorage(0);
    CvSeq *imageKeypoints, *imageDescriptors;

	cvExtractSURF( grayImage, 0, &imageKeypoints, &imageDescriptors, imageStorage, cvSURFParams(500,1) );

	CvPoint src_corners[4] = {{0,0}, {_orgWidth,0}, {_orgWidth, _orgHeight}, {0, _orgHeight}};
	CvPoint dst_corners[4];

	if( LocatePlanarObject( _objectKeypoints, _objectDescriptors, imageKeypoints, imageDescriptors, src_corners, dst_corners ) ) {
		_recognitionResult.resize(1);

		_recognitionResult[0].name = _objName;
		_recognitionResult[0].point1X = dst_corners[0].x;
		_recognitionResult[0].point1Y = dst_corners[0].y;
		_recognitionResult[0].point2X = dst_corners[1].x;
		_recognitionResult[0].point2Y = dst_corners[1].y;
		_recognitionResult[0].point3X = dst_corners[2].x;
		_recognitionResult[0].point3Y = dst_corners[2].y;
		_recognitionResult[0].point4X = dst_corners[3].x;
		_recognitionResult[0].point4Y = dst_corners[3].y;
		//PrintMessage("KitechSurfObjectRecognitionComp::recognize() -> I found data.(%s)\n", _recognitionResult[0].name.c_str());
	}

	cvReleaseMemStorage( &imageStorage );

	cvReleaseImage( &grayImage );
	cvReleaseImageHeader( &cvImage );

	return _recognitionResult;
}
Beispiel #21
0
/**
Finds SIFT features in an image using user-specified parameter values.  All
detected features are stored in the array pointed to by \a feat.

@param img the image in which to detect features
@param fea a pointer to an array in which to store detected features
@param intvls the number of intervals sampled per octave of scale space
@param sigma the amount of Gaussian smoothing applied to each image level
	before building the scale space representation for an octave
@param cont_thr a threshold on the value of the scale space function
	\f$\left|D(\hat{x})\right|\f$, where \f$\hat{x}\f$ is a vector specifying
	feature location and scale, used to reject unstable features;  assumes
	pixel values in the range [0, 1]
@param curv_thr threshold on a feature's ratio of principle curvatures
	used to reject features that are too edge-like
@param img_dbl should be 1 if image doubling prior to scale space
	construction is desired or 0 if not
@param descr_width the width, \f$n\f$, of the \f$n \times n\f$ array of
	orientation histograms used to compute a feature's descriptor
@param descr_hist_bins the number of orientations in each of the
	histograms in the array used to compute a feature's descriptor

@return Returns the number of keypoints stored in \a feat or -1 on failure
@see sift_keypoints()
*/
int _sift_features( IplImage* img, struct feature** feat, int intvls,
		   double sigma, double contr_thr, int curv_thr,
		   int img_dbl, int descr_width, int descr_hist_bins )
{
	IplImage *init_img;
	IplImage ***gauss_pyr, ***dog_pyr;
	CvMemStorage *storage;
	CvSeq *features;
	int octvs, i, n = 0;

	/* build scale space pyramid; smallest dimension of top level is ~4 pixels */
	init_img = create_init_img( img, img_dbl, sigma );
	octvs = log( MIN( init_img->width, init_img->height ) ) / log(2) - 2;
	gauss_pyr = build_gauss_pyr( init_img, octvs, intvls, sigma );
	dog_pyr = build_dog_pyr( gauss_pyr, octvs, intvls );

	storage = cvCreateMemStorage( 0 );
	features = scale_space_extrema( dog_pyr, octvs, intvls, contr_thr, curv_thr, storage );
	calc_feature_scales( features, sigma, intvls );
	if( img_dbl )
		adjust_for_img_dbl( features );
	calc_feature_oris( features, gauss_pyr );
	compute_descriptors( features, gauss_pyr, descr_width, descr_hist_bins );

	/* sort features by decreasing scale and move from CvSeq to array */
	cvSeqSort( features, (CvCmpFunc)feature_cmp, NULL );
	n = features->total;
	*feat = calloc( n, sizeof(struct feature) );
	*feat = cvCvtSeqToArray( features, *feat, CV_WHOLE_SEQ );
	for( i = 0; i < n; i++ ) {
		free( (*feat)[i].feature_data );
		(*feat)[i].feature_data = NULL;
	}

	cvReleaseMemStorage( &storage );
	cvReleaseImage( &init_img );
	release_pyr( &gauss_pyr, octvs, intvls + 3 );
	release_pyr( &dog_pyr, octvs, intvls + 2 );
	return n;
}
Beispiel #22
0
void EnclosingCircle(IplImage* _image, IplImage *dem)
{
        assert(_image != 0);

        IplImage* bin = cvCreateImage( cvGetSize(_image), IPL_DEPTH_8U, 1);

        // конвертируем в градации серого
        cvConvertImage(_image, bin, CV_BGR2GRAY);
        // находим границы
        cvCanny(bin, bin, 100, 200);

        //cvNamedWindow( "bin", 1 );
        //cvShowImage("bin", bin);

        // хранилище памяти для контуров
        CvMemStorage* storage = cvCreateMemStorage(0);
        CvSeq* contours = 0;

        // находим контуры
        int contoursCont = cvFindContours( bin, storage, &contours, sizeof(CvContour), CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0));

        assert(contours != 0);

        CvPoint2D32f center;
        float radius = 0;
        // обходим все контуры
        for( CvSeq* current = contours; current != NULL; current = current->h_next )
        {
                // находим параметры окружности
                cvMinEnclosingCircle(current, &center, &radius);
        
                // рисуем
                cvCircle(dem, cvPointFrom32f(center), radius, CV_RGB(255, 0, 0), 1, 1);
        }

        // освобождаем ресурсы
        cvReleaseMemStorage(&storage);
        cvReleaseImage(&bin);
}
Beispiel #23
0
//--------------------------------------------------------------
void Vision::checkHoles(){ //Duplicate the 1st part of findContour in ofxCvContourFinder Class
    // get width/height disregarding ROI
    ofxCvGrayscaleImage input = grayDiff;
    IplImage* ipltemp = input.getCvImage();
    
    int  _width;
    int  _height;
    
    _width = ipltemp->width;
    _height = ipltemp->height;
    
    ofxCvGrayscaleImage     inputCopy;
    inputCopy.setUseTexture(false);
	if( inputCopy.getWidth() == 0 ) {
		inputCopy.allocate( _width, _height );
	} else if( inputCopy.getWidth() != _width || inputCopy.getHeight() != _height ) {
        // reallocate to new size
        inputCopy.clear();
        inputCopy.allocate( _width, _height );
	}
    
    inputCopy.setROI( input.getROI() );
    inputCopy = input;
    
	CvSeq* contour_list = NULL;
	CvMemStorage* contour_storage = cvCreateMemStorage(1000);
    
	cvFindContours( inputCopy.getCvImage(), contour_storage, &contour_list,
                   sizeof(CvContour), CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);
    
    
    //-----------------------------------//
    cardDetection(contour_list);
    //-----------------------------------//
    
	// Free the storage memory.
	// Warning: do this inside this function otherwise a strange memory leak
	if( contour_storage != NULL ) { cvReleaseMemStorage(&contour_storage); }    
}
	// this should be replaced by c++ 2.0 api style code once available
	vector<cv::Vec4i> convexityDefects(const vector<cv::Point>& contour) {
		vector<int> hullIndices;
		convexHull(Mat(contour), hullIndices, false, false);
		vector<cv::Vec4i> convexityDefects;
		if(hullIndices.size() > 0 && contour.size() > 0) {		
			CvMat contourMat = cvMat(1, contour.size(), CV_32SC2, (void*) &contour[0]);
			CvMat hullMat = cvMat(1, hullIndices.size(), CV_32SC1, (void*) &hullIndices[0]);
			CvMemStorage* storage = cvCreateMemStorage(0);
			CvSeq* defects = cvConvexityDefects(&contourMat, &hullMat, storage);
			for(int i = 0; i < defects->total; i++){
				CvConvexityDefect* cur = (CvConvexityDefect*) cvGetSeqElem(defects, i);
				cv::Vec4i defect;
				defect[0] = cur->depth_point->x;
				defect[1] = cur->depth_point->y;
				defect[2] = (cur->start->x + cur->end->x) / 2;
				defect[3] = (cur->start->y + cur->end->y) / 2;
				convexityDefects.push_back(defect);
			}
			cvReleaseMemStorage(&storage);
		}
		return convexityDefects;
	}
void ofxCvHaarFinder::setup(string haarFile) {
	if(cascade != NULL)
		cvReleaseHaarClassifierCascade(&cascade);

	this->haarFile = haarFile;

	haarFile = ofToDataPath(haarFile);
	cascade = (CvHaarClassifierCascade*) cvLoad(haarFile.c_str(), 0, 0, 0);

	#ifdef HAAR_HACK
		// http://thread.gmane.org/gmane.comp.lib.opencv/16540/focus=17400
		// http://www.openframeworks.cc/forum/viewtopic.php?f=10&t=1853&hilit=haar
		ofxCvGrayscaleImage hack;
		hack.allocate(8, 8);
		CvMemStorage* storage = cvCreateMemStorage();
		cvHaarDetectObjects(hack.getCvImage(), cascade, storage, scaleHaar, 2, CV_HAAR_DO_CANNY_PRUNING);
		cvReleaseMemStorage(&storage);
	#endif

	if (!cascade)
		printf("Could not load Haar cascade: %s\n", haarFile.c_str());
}
JNIEXPORT void JNICALL Java_com_userinterface_OpenCV_extractSURFFeature(
		JNIEnv* env, jobject thiz) {
	IplImage *pWorkImage=cvCreateImage(cvGetSize(pImage),IPL_DEPTH_8U,1);
	cvCvtColor(pImage,pWorkImage,CV_BGR2GRAY);
	CvMemStorage* storage = cvCreateMemStorage(0);
	CvSeq *imageKeypoints = 0, *imageDescriptors = 0;
	CvSURFParams params = cvSURFParams(2000, 0);
	cvExtractSURF( pWorkImage, 0, &imageKeypoints, &imageDescriptors, storage, params );
	// show features
	for( int i = 0; i < imageKeypoints->total; i++ )
	{
		CvSURFPoint* r = (CvSURFPoint*)cvGetSeqElem( imageKeypoints, i );
		CvPoint center;
		int radius;
		center.x = cvRound(r->pt.x);
		center.y = cvRound(r->pt.y);
		radius = cvRound(r->size*1.2/9.*2);
		cvCircle( pImage, center, radius, CV_RGB(255,0,0), 1, CV_AA, 0 );
	}
	cvReleaseImage(&pWorkImage);
	cvReleaseMemStorage(&storage);
}
Beispiel #27
0
void
releaseBGMeanStatModel( BGMeanStatModel** _model ){
  CV_FUNCNAME( "releaseBGMeanStatModel" );
  
  __BEGIN__;
  
  if( !_model )
    CV_ERROR( CV_StsNullPtr, "" );
  
  if( *_model ){
    BGMeanStatModel* model = *_model;
    
    cvFree( &model->frame_cbuffer );
    cvFree( &model->mean );
    cvFree( &model->std_dev );
    cvReleaseImage( &model->foreground );
    cvReleaseImage( &model->background );
    cvReleaseMemStorage(&model->storage);
    cvFree( _model );
  }
  
  __END__;
}
void exit_nicely(char* msg)
{
	cvDestroyAllWindows();
	if (capture)
		cvReleaseCapture(&capture);
	if (gray)
		cvReleaseImage(&gray);
	if (prev)
		cvReleaseImage(&prev);
	if (diff)
		cvReleaseImage(&diff);
	if (tpl)
		cvReleaseImage(&tpl);
	if (storage)
		cvReleaseMemStorage(&storage);
	if (msg != NULL)
	{
		fprintf(stderr, msg);
		fprintf(stderr, "/n");
		exit(1);
	}
	exit(0);
}
Beispiel #29
0
//对序列中的每个元素进行操作,此序列的元素是由cvPyrSegmentation返回的连续区域
void f(
  IplImage* src, 
  IplImage* dst 
) {
//    分配存储区域,storage指针指向opencv存储区
  CvMemStorage* storage = cvCreateMemStorage(0);
//    序列的初始位置
  CvSeq* comp = NULL;
//    金字塔处理,参数分别为:输入、输出、存储、位置指针、金字塔层数、建立连接时的错误阈值,分割簇的错误阈值
//    建立连接时的错误阈值:小于等于该值得点连接;分割簇的错误阈值:小于等于该值的点看做一个区域
  cvPyrSegmentation( src, dst, storage, &comp, 4, 200, 50 );
//    获取序列元素的个数
  int n_comp = comp->total;

  for( int i=0; i<n_comp; i++ ) {
//      依次获得每一个元素的值
    CvConnectedComp* cc = (CvConnectedComp*) cvGetSeqElem( comp, i );
    // do_something_with( cc );
//      这里可以做点什么
  }
//    释放内存
  cvReleaseMemStorage( &storage );
}
Beispiel #30
0
ViennaMap::~ViennaMap() {
  SDL_mutex *mut = cvRessourcesGuard;

  //free cv ressources and their guard
  if (SDL_mutexP(mut) == -1) 
    throw "could not acquire cvRessourcesGuard to destruct ViennaMap";

  cvRessourcesGuard = 0;
  cvReleaseMemStorage(&cvMemStorage);
  cvReleaseImage(&tempBinarizedImage);
  

  if (SDL_mutexV(mut) == -1) 
    throw "could not release cvRessourcesGuard after freeing cv ressources";
  SDL_DestroyMutex(mut);

  //free fragments and their guard
  mut = fragmentGuard;
  if (SDL_mutexP(mut) == -1)
    throw "could not acquire fragment guard to destruct ViennaMap";

  fragmentGuard = 0;
  std::vector<MapFragment*>::iterator it=fragments.begin(), end = fragments.end();
  for(;it != end; it++)
    if (*it != NULL) {
      freePolygonList((*it)->polygons);
      freePolygonList((*it)->incompletePolygons);
      delete *it;
      *it = NULL;
    }

  fragments.clear();

  if (SDL_mutexV(mut) == -1)
    throw "could not release fragmentGuard after freeing fragments";
  
}