将图像进行二值化处理的C++程序源代码

我测试过了,可用!

#include “cv.h”‘
#include “cxcore.h”
#include “highgui.h”
#include <iostream>
using namespace std;
int main ()
{
    IplImage* img = cvLoadImage(“asdf.jpg”,-1);
    IplImage* biimg = cvCreateImage(cvGetSize(img),img->depth,img->nChannels);
    CvScalar s;
    int sum=0;
    for (int i=0;i<img->height;i++)
    {
        for (int j=0;j<img->width;j++)
        {
            s =  cvGet2D(img,i,j);
            //cout<<s.val[0]<<” “<<s.val[1]<<” “<<s.val[2]<<endl;
            sum = (s.val[0]+s.val[1]+s.val[2])/3;
            if (sum > 128)
            {
                s.val[0]=s.val[1]=s.val[2]=255;
                cvSet2D(img,i,j,s);
            }
            else
            {
                s.val[0]=s.val[1]=s.val[2]=0;
                cvSet2D(img,i,j,s);

            }
        }
    }
    cvCopy(img,biimg);
    cvSaveImage(“combibi.JPG”,biimg);
    cvNamedWindow(“imagebinary”);
    cvShowImage(“imagebinary”,biimg);
    cvWaitKey(0);
    cvDestroyWindow(“imagebinary”);
    cvReleaseImage(&img);
    cvReleaseImage(&biimg);
}

Leave a Reply