1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83
| #include "main.h"
#include <cv.h>
#include <highgui.h>
#include <stdio.h>
#include <cxcore.h>
#include "cxcore.h"
#include "highgui.h"
#include <algorithm>
using namespace std;
int main()
{
IplImage *src=cvLoadImage("PolyU_014_S_03.bmp");
CvSize size_src=cvSize(src->width,src->height);
IplImage *PlaneB=cvCreateImage(size_src,src->depth,1);
IplImage *PlaneG=cvCreateImage(size_src,src->depth,1);
IplImage *PlaneR=cvCreateImage(size_src,src->depth,1);
cvCvtPixToPlane(src,PlaneB,PlaneG,PlaneR,0);
IplImage *dst=cvCreateImage(size_src,IPL_DEPTH_8U,1);
int* cluster,nvector=0, i, ncluster=2;
CvVect32f *samples;
cluster=(int*)malloc((src->width)*(src->height)*sizeof(int));
samples=(CvVect32f *)malloc((src->width)*(src->height)*sizeof(CvVect32f));
CvTermCriteria termcrit;
termcrit.type=CV_TERMCRIT_ITER +CV_TERMCRIT_EPS;
termcrit.max_iter=10;
termcrit.epsilon=1.0;
CvScalar pixel_mask;
for(i=0;i<PlaneB->height;i++)
{
for(int j=0;j<PlaneB->width;j++)
{samples[nvector]=(CvVect32f)malloc(3*sizeof(float));
pixel_mask =cvGet2D( PlaneB, j, i);
samples[nvector][0]=pixel_mask.val[0];
pixel_mask =cvGet2D( PlaneG, j, i);
samples[nvector][1]=pixel_mask.val[0];
pixel_mask =cvGet2D( PlaneR, j, i);
samples[nvector][2]=pixel_mask.val[0];
nvector++;
}
}
cvKMeans(ncluster,samples,(src->width)*(src->height),3,termcrit,cluster);
float step=255/(float)ncluster;
CvScalar pixel;
nvector=0;
for(i=0;i<dst->height;i++)
{
for(int j=0;j<dst->width;j++)
{
pixel.val[0]= step*cluster[nvector]; // on insère la valeur voulu
// dans le 1er canal (les autres ont une valeur de 0 par défaut)
cvSet2D (dst,j,i,pixel);
nvector++;
}
}
cvSaveImage("km.bmp",dst);
cvWaitKey(0);
cvNamedWindow("window src",CV_WINDOW_AUTOSIZE);
cvShowImage("window src",src);
cvNamedWindow("window dst",CV_WINDOW_AUTOSIZE);
cvShowImage("window dst",dst);
nvector=0;
for(i=0;i<PlaneB->height;i++)
{
for(int j=0;j<PlaneB->width;j++)
{
free(samples[nvector]);
nvector++;
}
}
free(samples);
free(cluster);
cvDestroyWindow("window src");
cvDestroyWindow("window dst");
cvReleaseImage(&src);
cvReleaseImage(&dst);
} |
Partager