Wednesday, October 29, 2008

[OpenCV]: use cvPyrSegmentation

#include <stdio.h>
#include <cv.h>
#include <highgui.h>
#include <stdio.h>

void f(
IplImage* src,
IplImage* dst
) {
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 );

int main(int argc, char** argv)

// Create a named window with a the name of the file.
cvNamedWindow( argv[1], 1 );
// Load the image from the given file name.
IplImage* src = cvLoadImage( argv[1] );
if(!src) { printf("Couldn't seem to Open %s, sorry\n",argv[1]); return -1;}
IplImage* dst = cvCreateImage( cvGetSize(src), src->depth, src->nChannels);
f( src, dst);

// Show the image in the named window
cvShowImage( argv[1], dst );

// Idle until the user hits the "Esc" key.
while( 1 ) { if( cvWaitKey( 100 ) == 27 ) break; }

// Clean up and don’t be piggies
cvDestroyWindow( argv[1] );
cvReleaseImage( &src );
cvReleaseImage( &dst );

code from 'learning opencv' book


  1. Hi Weiz,

    I tried to run your program "cvPyrSegmentation", but I got an error.
    It says that the "cvPyrSegmentation" function has a bad argument, but the code is identical to yours.
    Do you know what's wrong?

    Best Regards.


  2. Anonymous6:10 AM

    I have the same problem!!
    Does Everybody know something about it?

  3. This comment has been removed by the author.

  4. Anonymous3:44 PM

    your image size was probably the problem.

    The 5th argument (level) cannot be larger than the number of times the smallest dimension of the image is divisible by 2.

    imagesize = 1024x1024
    level can be any integer between 1 and 10

    imagesize = 1024x512
    level can be any integer between 1 and 9

    imagesize = 80 x 1000
    level can be any integer between 1 and 4

  5. Anonymous3:50 PM

    ...with the argument of 4 for level, the image you were processing had to have a smallest dimension (width or height) that was a multiple of 16 = 2x2x2x2

  6. Anonymous3:27 PM

    Yeah, check pyramid_segmentation.c in OpenCV\samples\c. You can also resize your image first using

    image->width &= -(1<height &= -(1<<level)

    where level is your level argument to cvPyrSegmentation()

  7. Anonymous3:29 PM

    Hmm, that didn't come out right above. That should read:

    image->width &= -(1 << level)
    image->height &= -(1 << level)