12. 对一幅灰度图像用最大类间方差法求阈值,并对其进行二值化。
#include <cv.h> #include <highgui.h> #define GrayScale 256 int mytsu( IplImage *frame); int main() { int a=0; IplImage * test; IplImage * test_1; test = cvLoadImage("6013202130.bmp", 0);//图片路径是 ConsoleApplication4 文件夹里,同时实验要求转为灰度图片 test_1 = cvCreateImage(cvSize((test->width), (test->height)), IPL_DEPTH_8U, 1); //创建图像,给指针赋值 a= mytsu(test); CvScalar s; for (int i = 0; i < test->height; i++) { for (int j = 0; j < test->width; j++) { s = cvGet2D(test, i, j); if (s.val[0] >a) s.val[0] = 255; else s.val[0] = 0; cvSet2D(test_1, i, j, s); } } cvNamedWindow("原图—6013202130", CV_WINDOW_AUTOSIZE); cvShowImage("原图—6013202130", test); cvNamedWindow("对数变换—6013202130", CV_WINDOW_AUTOSIZE); cvShowImage("对数变换—6013202130", test_1); cvWaitKey(0);//等待按键 cvDestroyWindow("原图—6013202130"); cvDestroyWindow("对数变换—6013202130"); cvReleaseImage(&test);//释放内存。 cvReleaseImage(&test_1); return 0; } int mytsu( IplImage *frame) { int width = frame->width; int height = frame->height; int pixelCount[GrayScale] = { 0 }; float pixelPro[GrayScale] = { 0 }; int i, j, pixelSum = width * height, threshold = 0; uchar* data = (uchar*)frame->imageData; //统计每个灰度级中像素的个数 for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { pixelCount[(int)data[i * width + j]]++; } } //计算每个灰度级的像素数目占整幅图像的比例 for (i = 0; i < GrayScale; i++) { pixelPro[i] = (float)pixelCount[i] / pixelSum; } //遍历灰度级[0,255],寻找合适的threshold float w0, w1, u0tmp, u1tmp, u0, u1, deltaTmp, deltaMax = 0; for (i = 0; i < GrayScale; i++) { w0 = w1 = u0tmp = u1tmp = u0 = u1 = deltaTmp = 0; for (j = 0; j < GrayScale; j++) { if (j <= i) //背景部分 { w0 += pixelPro[j]; u0tmp += j * pixelPro[j]; } else //前景部分 { w1 += pixelPro[j]; u1tmp += j * pixelPro[j]; } } u0 = u0tmp / w0; u1 = u1tmp / w1; deltaTmp = (float)(w0 *w1* pow((u0 - u1), 2)); if (deltaTmp > deltaMax) { deltaMax = deltaTmp; threshold = i; } } return threshold; }
声明:
博主是原悦乎教程网站长,博主写博客花费了大量精力,我的博客欢迎转载共享,但在 同时,希望保留我的署名权,不得用于商业用途。转载时请注明转载地址。未经特别说明,均采用“署名-非商业性使用-禁止演绎 2.5 中国大陆”授权。任何违反本协议的行为均属于非法行为。