OpenCV中如何只对IplImage图像的数据进行处理

来源:互联网 发布:java服务器端部署 编辑:程序博客网 时间:2024/06/10 02:26
//此程序的功能是实现对IplImage的imageData进行操作
//将src的数据拷贝给dst
#include "StdAfx.h"
#include <iostream.h>
#include <stdio.h>


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


int Otsu(uchar* src,uchar* dst,const int src_width,const int src_height); 


int main(int argc, char* argv[])
{
const char* filename = argc >= 2 ? argv[1] : "cir1.bmp";
IplImage* src = cvLoadImage( filename, 0 ); 
IplImage* dst = cvCreateImage(cvSize(src->width,src->height),IPL_DEPTH_8U,1);
cvNamedWindow( "Resource", CV_WINDOW_AUTOSIZE );
cvNamedWindow( "Dst", CV_WINDOW_AUTOSIZE );
int height = src->height;
int width  = src->width;
int Th = 0;
//********************
uchar* pSrc=NULL;
uchar* pDst=NULL;
pSrc=(uchar*)src->imageData;
pDst=(uchar*)dst->imageData;
Th = Otsu(pSrc,pDst,width,height);
printf("Th=%d\n",Th);
//********************
dst->imageData=(char*)pDst;
cvShowImage("Resource",src);
cvShowImage("Dst",dst);
cvWaitKey(0);
cvReleaseImage(&src);
cvReleaseImage(&dst);
cvDestroyWindow("Resource");
cvDestroyWindow("Dst");
return 0;
}


int Otsu(uchar* src,uchar* dst,const int src_width,const int src_height)
{
int step = 0;
int i = 0,j = 0;
int width = src_height,height = src_width;
long int N = height * width;
int T = 0;
int    h[256] = {0};
double p[256] = {0};
double u[256] = {0};
double w[256] = {0};
double uT = 0.0,sigma2fang = 0.0;
double sigma2fang_max = -10000;


if(NULL == src || 0 == src_width || 0 == src_height)
{
return -1;
}


cout<<"Otsu function begin!"<<endl;
cout<<"src_width="<<src_width<<" src_height="<<src_height<<endl;


if(0 == width%4)
{
step=width/sizeof(uchar);
}
else
{
step=(width- width%4 + 4)/sizeof(uchar);
}


cout<<"src_step="<<step<<endl;
/*
for(i=0; i<height; i++)
{
for(j=0; j<width; j++)
{
*(dst + step*i+j)= *(src + step*i+j); 
}
}*/


//calculate histogram
for(i = 0; i < height; i++)
{
for(int j = 0; j < width; j++)
{
for(int k = 0; k < 256; k++)
{
if(((uchar*)(src + step*i))[j] == k)
h[k]++;
}
}


//calculate ratio of every bin 
    for(i = 0; i < 256; i++)
{
p[i] = h[i] / double(N);
}       


for(int k = 0; k < 256; k++)
{
uT = 0;


for(i = 0; i <= k; i++)
{
w[k] += p[i];
u[k] += i*p[i];
}


for(i = 0; i < 256; i++)
{
uT += i*p[i];
}


sigma2fang = (uT*w[k] - u[k])*(uT*w[k] - u[k]) / (w[k]*(1-w[k]));


if(sigma2fang > sigma2fang_max)
{
sigma2fang_max = sigma2fang;
T = k;
}
}
 
for(i = 0; i < height; i++)   
{
for(int j = 0; j < width; j++)
{
if(((uchar*)(src + step*i))[j] > T)
{
((uchar*)(dst + step*i))[j] = 255;
}
else
{
((uchar*)(dst + step*i))[j] = 0;
}
}
}
return T;
}
原创粉丝点击