Skip to content

Instantly share code, notes, and snippets.

@josch
Created October 18, 2012 14:21
Show Gist options
  • Save josch/3912162 to your computer and use it in GitHub Desktop.
Save josch/3912162 to your computer and use it in GitHub Desktop.
cvPyrSegmentation example
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include <iostream>
using namespace cv;
using namespace std;
Mat res, element;
int main(int argc, char** argv)
{
namedWindow( "window", CV_WINDOW_NORMAL );
CvSeq *comp;
CvMemStorage *storage;
IplImage *image, *src, *dst;
int levels, block_size;
double thresh1, thresh2;
image = cvLoadImage(argv[1]);
src = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
cvCvtColor(image, src, CV_RGB2GRAY);
dst = cvCreateImage(cvGetSize(image), IPL_DEPTH_8U, 1);
cout << "depth: " << src->depth << " channels: " << src->nChannels << endl;
block_size = 1000;
storage = cvCreateMemStorage(block_size);
comp = NULL;
levels = 2;
thresh1 = 50;
thresh2 = 50;
/* this is mandatory */
src->width = dst->width = (image->width & -(1 << levels));
src->height = dst->height = (image->height & -(1 << levels));
cvPyrSegmentation(src, dst,
storage, &comp,
levels, thresh1, thresh2);
int n_comp = comp->total;
// mapping of color value to component id
map<int, int> mapping;
for (int i = 0; i < n_comp; i++) {
// only the first value of the scalar contains information as we
// handle 1 channel gray scale images
CvConnectedComp* cc = (CvConnectedComp*)cvGetSeqElem(comp, i);
mapping.insert(pair<int, int>(cc->value.val[0], i));
}
uchar *data = (uchar *)dst->imageData;
int step = dst->widthStep;
for (int i = 0; i < dst->height; i++) {
for (int j = 0; j < dst->width; j++) {
uchar val = data[i*step+j];
cout << "x,y,C: " << j << "," << i << "," << mapping[val] << endl;
}
}
cvReleaseMemStorage(&storage);
cvShowImage("Pyr Segmentation", dst);
waitKey();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment