图形图像实验-二值分割代码

来源:互联网 发布:长城软件怎么样 编辑:程序博客网 时间:2024/05/22 15:57
最大类间方差分割
迭代阈值分割:进行多次循环,多次计算最佳阈值T= (m1+m2)/2;
首先随机选择一个阈值作为判断标准,遍历所有像素点,用阈值分割图像成为两组像素,G1由大于阈值的像素点组成,
G2由小于阈值的像素点组成。计算G1和G2像素的平均灰度m1和m2
新的阈值(m1+m2)/2
用阈值差作为迭代的出口
// 二值分割.cpp : Defines the entry point for the console application.//#include "stdafx.h"#include "cv.h"#include "highgui.h"#include <math.h>#include <memory.h>#include <stdio.h>#include <iostream>using namespace std;int GetPixel(int i, int j,IplImage *pImage,int rgb){return (int)((uchar*)(pImage->imageData+j*pImage->widthStep))[rgb*i];//pImage->imageData是指这个图像的首地址,pImage->widthStep是每个图像所占用的字节数}void SetPixel(int i, int j,IplImage *pImage,float vaule,int rgb){((uchar*)(pImage->imageData+j*pImage->widthStep))[rgb*i] = vaule;}int GetThreshold (IplImage *pImage){int i,j,threshold = 128,dif=128,threshold2 ;int totol = pImage->width*pImage->height;cout<<"像素总数"<<totol<<endl;while(dif>=5){// int low[totol/2],high[totol/2];int k=0,l =0;int lowSum = 0,highSum = 0;//lowM,highM,middle;for(i = 1;i< pImage->width -1;i++){for(j = 1;j< pImage ->height-1;j++){if(GetPixel(i,j,pImage,1) < threshold){lowSum = lowSum + GetPixel(i,j,pImage,1);k++;}else{highSum=GetPixel(i,j,pImage,1)+highSum;l++;}}}// for(i = 0;i<k;i++){// lowSum = lowSum +low[i];// }// for(j = 0;j<l;j++){// highSum = highSum + high[j];// }threshold2 = (lowSum/k+highSum/l)/2;dif = abs(threshold2- threshold);cout<<"未跳出"<<dif<<endl;threshold = threshold2;}cout<<"跳出了"<<dif<<endl;return threshold;}void GetHandleImage(int threshold,IplImage *pImage,IplImage *afterImage){int i,j;for(i = 0;i< pImage->width -1;i++){for(j = 0;j< pImage ->height-1;j++){if(GetPixel(i,j,pImage,1) <threshold){SetPixel(i,j,afterImage,0,1);}else{SetPixel(i,j,afterImage,255,1);}}}}int main(int argc, char* argv[]){int threshold = 0;const char* imagepath = "2.jpg";IplImage *pImage;pImage = cvLoadImage(imagepath,0);IplImage *afterImage = cvCloneImage(pImage);cvNamedWindow("原图");cvShowImage( "原图", pImage);threshold = GetThreshold(pImage);GetHandleImage(threshold,pImage,afterImage);cvNamedWindow("二值分割");cvShowImage("二值分割",afterImage);cvWaitKey();cvReleaseImage(&pImage);cvDestroyWindow("原图");cvDestroyWindow("二值分割");return 0;}


0 0
原创粉丝点击