您的位置:首页 > 其它

Adaptive thresholding using the integral image

2017-04-02 12:06 302 查看
#include <opencv2/opencv.hpp>

#include <opencv2/legacy/compat.hpp>

#include <opencv2/imgproc/types_c.h>

#include <fstream>

using namespace std;

void vvAdaptiveThreshold( IplImage* inImg, IplImage* outImg)

{

int S = inImg->width >> 5;

int T = 10;

char *input, *bin;

input = inImg->imageData;

bin = outImg->imageData;

int width = inImg->width;

int height = inImg->height;

unsigned long* integralImg = 0;

int i, j;

long sum=0;

int count=0;

int index;

int x1, y1, x2, y2;

int s2 = S/2;

//bin = new unsigned char[width*height];

// create the integral image

integralImg = (unsigned long*)malloc(width*height*sizeof(unsigned long*));

for (i=0; i<width; i++)

{

// reset this column sum

sum = 0;

for (j=0; j<height; j++)

{

index = j*width+i;

sum += input[index];

if (i==0)

integralImg[index] = sum;

else

integralImg[index] = integralImg[index-1] + sum;

}

}

// perform thresholding

for (i=0; i<width; i++)

{

for (j=0; j<height; j++)

{

index = j*width+i;

// set the SxS region

x1=i-s2; x2=i+s2;

y1=j-s2; y2=j+s2;

// check the border

if (x1 < 0) x1 = 0;

if (x2 >= width) x2 = width-1;

if (y1 < 0) y1 = 0;

if (y2 >= height) y2 = height-1;

count = (x2-x1)*(y2-y1);

// I(x,y)=s(x2,y2)-s(x1,y2)-s(x2,y1)+s(x1,x1)

sum = integralImg[y2*width+x2] -

integralImg[y1*width+x2] -

integralImg[y2*width+x1] +

integralImg[y1*width+x1];

if ((long)(input[index]*count) < (long)(sum*(100-T)/100))

bin[index] = 255;

else

bin[index] = 0;

}

}

free (integralImg);

}

int main() //欢迎大家加入图像识别技术交流群:271891601

{

// 从文件中加载原图

//IplImage *pSrcImage1 = cvLoadImage("adaptive.jpg", CV_LOAD_IMAGE_UNCHANGED);

IplImage *pSrcImage1 = cvLoadImage("ding9.jpeg", CV_LOAD_IMAGE_UNCHANGED);

IplImage *pSrcImage = cvCreateImage(cvGetSize(pSrcImage1), IPL_DEPTH_8U,1);

cvCvtColor(pSrcImage1,pSrcImage,CV_BGR2GRAY);//cvCvtColor(src,des,CV_BGR2GRAY)

//创建输出的图像

IplImage *pOutImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U,1);

vvAdaptiveThreshold(pSrcImage,pOutImage);

const char *pstrWindowsATitle = "Adptive Thresholding using the Integral Image";

cvNamedWindow(pstrWindowsATitle, CV_WINDOW_AUTOSIZE);

cvShowImage(pstrWindowsATitle, pOutImage);

const char *pstrWindowsATitle1 = "origial Image";

cvNamedWindow(pstrWindowsATitle1, CV_WINDOW_AUTOSIZE);

cvShowImage(pstrWindowsATitle1, pSrcImage1);

cvWaitKey(0);

//这里记得释放掉不用的资源哦,由于这是测试程序,就不写了,正式的程序一定要写上哦

return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: