opencv图像处理基本操作

1:读取图片

#include <cv.h>
#include <highgui.h>
int main()
{
    IplImage *img = 0;
    img = cvLoadImage("/home/todayac/Desktop/img/test.jpg",-1);
    cvNamedWindow("lena", 1);
    cvShowImage("lena", img);
    cvWaitKey(0);
    return 0;

}



2:把RGB图片的灰度处理


#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv/cv.h>
#include <cstdio>
using namespace cv;

void RGB2GRAY(IplImage* src){
    //创建2个窗体,分别显示源图像和处理后的灰度图
    cvNamedWindow("RGB");
    cvNamedWindow("GRAY");
    //显示源图像
    cvShowImage("RGB",src);
    //创建一个源图像一样的IplImage指针
    IplImage* dst = cvCreateImage(cvGetSize(src),src->depth,1);
    //色彩空间转换,转换类型为CV_BGR2GRAY
    cvCvtColor(src,dst,CV_BGR2GRAY);
    //显示灰度图
    cvShowImage("GRAY",dst);
    //释放资源
    cvSaveImage("/home/todayac/Desktop/img/test2.jpg",dst);

    cvReleaseImage(&dst);
    cvWaitKey(0);
    cvDestroyWindow("RGB");
    cvDestroyWindow("GRAY");
}

//主函数
int main(int argc, char** argv){

    IplImage* img = cvLoadImage("/home/todayac/Desktop/img/test1.jpg");
    RGB2GRAY(img);
    while(1){
        if(cvWaitKey(100)==27)
            break;
    }
    cvReleaseImage(&img);
    return 0;
}




3:图像二值化


//图像的二值化
#include <opencv2/opencv.hpp>
#include <cv.h>
#include <iostream>
#include <cstdio>

using namespace cv;
using namespace std;

IplImage *g_pGrayImage = NULL;
IplImage *g_pBinaryImage = NULL;

const char *pstrWindowsBinaryTitle = "二值图";

void on_trackbar(int pos)
{
    // 转为二值图
    cvThreshold(g_pGrayImage, g_pBinaryImage, pos, 255, CV_THRESH_BINARY);
    // 显示二值图
    cvShowImage(pstrWindowsBinaryTitle, g_pBinaryImage);
}

int main( int argc, char** argv )
{
    const char *pstrWindowsSrcTitle = "/home/todayac/Desktop/img/test1.jpg";
    const char *pstrWindowsToolBarName = "255";

    // 从文件中加载原图
    IplImage *pSrcImage = cvLoadImage("/home/todayac/Desktop/img/test1.jpg", CV_LOAD_IMAGE_UNCHANGED);

    // 转为灰度图
    g_pGrayImage =  cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
    cvCvtColor(pSrcImage, g_pGrayImage, CV_BGR2GRAY);

    // 创建二值图
    g_pBinaryImage = cvCreateImage(cvGetSize(g_pGrayImage), IPL_DEPTH_8U, 1);

    // 显示原图
    cvNamedWindow(pstrWindowsSrcTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsSrcTitle, pSrcImage);
    // 创建二值图窗口
    cvNamedWindow(pstrWindowsBinaryTitle, CV_WINDOW_AUTOSIZE);
    // 滑动条
    int nThreshold = 120;
    cvCreateTrackbar(pstrWindowsToolBarName, pstrWindowsBinaryTitle, &nThreshold, 254, on_trackbar);

    on_trackbar(1);

    cvWaitKey(0);

    cvDestroyWindow(pstrWindowsSrcTitle);
    cvDestroyWindow(pstrWindowsBinaryTitle);
    cvReleaseImage(&pSrcImage);
    cvReleaseImage(&g_pGrayImage);
    cvReleaseImage(&g_pBinaryImage);
    return 0;
}


4:图像的压缩


#include <iostream>
#include <fstream>
#include <cv.h>
#include <highgui.h>
using namespace std;
using namespace cv;

double getPSNR(Mat& src1, Mat& src2, int bb=0);


int main(int argc, char** argv){

    Mat src = imread("/home/todayac/Desktop/img/test1.jpg");

    cout<<"origin image size: "<<src.dataend-src.datastart<<endl;
    cout<<"height: "<<src.rows<<endl<<"width: "<<src.cols<<endl<<"depth: "<<src.channels()<<endl;
    cout<<"height*width*depth: "<<src.rows*src.cols*src.channels()<<endl<<endl;

    //(1)jpeg压缩
    vector<uchar> buff;//buffer for coding
    vector<int> param = vector<int>(2);
    param[0]=CV_IMWRITE_JPEG_QUALITY;
    param[1]=95;//default(95) 0-100

    imencode(".jpg",src,buff,param);

    cout<<"coded file size(jpg): "<<buff.size()<<endl;//自动拟合大小。

    Mat jpegimage = imdecode(Mat(buff),CV_LOAD_IMAGE_COLOR);

    //(2) intaractive jpeg compression
    namedWindow("jpg");
    int q=90;
    createTrackbar("压缩比率","jpg",&q,100);
    int key = 0;

    while(key!='q')
    {
        param[0]=CV_IMWRITE_JPEG_QUALITY;
        param[1]=q;
        imencode(".jpg",src,buff,param);
        Mat show = imdecode(Mat(buff),CV_LOAD_IMAGE_COLOR);
        imshow("jpg",show);
        imwrite("/home/todayac/Desktop/img/test12.jpg",show);
        key = waitKey(33);

    }
}




double getPSNR(Mat& src1, Mat& src2, int bb){

    int i,j;
    double sse,mse,psnr;
    sse = 0.0;

    Mat s1,s2;
    cvtColor(src1,s1,CV_BGR2GRAY);
    cvtColor(src2,s2,CV_BGR2GRAY);

    int count=0;
    for(j=bb;j<s1.rows-bb;j++) {
        uchar* d=s1.ptr(j);
        uchar* s=s2.ptr(j);

        for(i=bb;i<s1.cols-bb;i++){
            sse += ((d[i] - s[i])*(d[i] - s[i]));
            count++;
        }
    }
    if(sse == 0.0 || count==0){
        return 0;
    } else{
        mse =sse /(double)(count);
        psnr = 10.0*log10((255*255)/mse);
        return psnr;
    }
}





5:图像直方处理对图像加强

#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>

#include <cstdio>
#include <cstring>
#include <iostream>

using namespace cv;
using namespace std;

int ImageStretchByHistogram(IplImage *src,IplImage *dst);


int main(){

    IplImage* pImg = 0;
    pImg=cvLoadImage("/home/todayac/Desktop/img/test1.jpg",-1);
    //创建一个灰度图像
    IplImage* GrayImage = cvCreateImage(cvGetSize(pImg), IPL_DEPTH_8U, 1);
    IplImage* dstGrayImage = cvCreateImage(cvGetSize(pImg), IPL_DEPTH_8U, 1);
    cvCvtColor(pImg, GrayImage, CV_BGR2GRAY);

    ImageStretchByHistogram(GrayImage,dstGrayImage);

    cvNamedWindow( "dstGrayImage", 1 ); //创建窗口
    cvNamedWindow( "GrayImage", 1 ); //创建窗口
    cvShowImage( "dstGrayImage", dstGrayImage ); //显示图像
    cvShowImage( "GrayImage", GrayImage ); //显示图像

     Mat show = Mat(dstGrayImage);
    imwrite("/home/todayac/Desktop/img/test12.jpg",show);

   // imwrite("/home/todayac/Desktop/img/test13.jpg",dstGrayImage);

    cvWaitKey(0); //等待按键

    cvDestroyWindow( "dstGrayImage" );//销毁窗口
    cvDestroyWindow( "GrayImage" );//销毁窗口
    cvReleaseImage( &pImg ); //释放图像
    cvReleaseImage( &GrayImage ); //释放图像
    cvReleaseImage( &dstGrayImage ); //释放图像

    return 0;
}

int ImageStretchByHistogram(IplImage *src,IplImage *dst)
/*************************************************
   根据直方图进行图像增强,将图像灰度的域值拉伸到0-255
   Input: 单通道灰度图像
   Output: 同样大小的单通道灰度图像
*************************************************/
{
    //p[]存放图像各个灰度级的出现概率;
    //p1[]存放各个灰度级之前的概率和,用于直方图变换;
    //num[]存放图象各个灰度级出现的次数;

    assert(src->width==dst->width);
    float p[256],p1[256],num[256];
    //清空三个数组
    memset(p,0,sizeof(p));
    memset(p1,0,sizeof(p1));
    memset(num,0,sizeof(num));

    int height=src->height;
    int width=src->width;
    long wMulh = height * width;

    //求存放图象各个灰度级出现的次数
    for(int x=0; x < src->width; x++ ){
        for(int y=0; y < src->height; y++ ) {
            uchar v=((uchar*)(src->imageData + src->widthStep*y))[x];
            num[v]++;
        }
    }

    //求存放图像各个灰度级的出现概率
    for(int i=0;i<256;i++) {
        p[i]=num[i]/wMulh;
    }

    //求存放各个灰度级之前的概率和
    for(int i=0;i<256;i++){
        for(int k=0;k<=i;k++)
            p1[i]+=p[k];
    }

    //直方图变换
    for(int x=0; x < src->width; x++ ){
        for(int y=0; y < src->height; y++ ) {
            uchar v=((uchar*)(src->imageData + src->widthStep*y))[x];
            ((uchar*)(dst->imageData + dst->widthStep*y))[x]= p1[v]*255+0.5;
        }
    }

    return 0;
}


6:熟悉Mat的一些遍历

#include <opencv/cv.h>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <cstdio>
#include <iostream>

using namespace std;
using namespace cv;

/***************************************************************
*
*    内容摘要:本例采用8种方法对图像Mat的像素进行扫描,并对像素点的像
*            素进行压缩,压缩间隔为div=64,并比较扫描及压缩的效率,效
*            率最高的是采用.ptr及减少循环次数来遍历图像,并采用位操
*            作来对图像像素进行压缩。
***************************************************************/

//利用.ptr和数组下标进行图像像素遍历
void colorReduce0(Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols * image.channels();

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            data[i] = data[i]/div*div+div/2;     //减少图像中颜色总数的关键算法:if div = 64, then the total number of colors is 4x4x4;整数除法时,是向下取整。
        }
    }
}


//利用.ptr和 *++ 进行图像像素遍历
void colorReduce1(Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols * image.channels();

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            *data++ = *data/div*div + div/2;
        }
    }
}


//利用.ptr和数组下标进行图像像素遍历,取模运算用于减少图像颜色总数
void colorReduce2(Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols * image.channels();

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            data[i] = data[i]-data[i]%div +div/2;  //利用取模运算,速度变慢,因为要读每个像素两次
        }
    }
}

//利用.ptr和数组下标进行图像像素遍历,位操作运算用于减少图像颜色总数
void colorReduce3(Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols * image.channels();

    int n = static_cast<int>(log(static_cast<double>(div))/log(2.0));   //div=64, n=6
    uchar mask = 0xFF<<n;                                            //e.g. div=64, mask=0xC0

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            *data++ = *data&mask + div/2;
        }
    }
}

//形参传入const conference,故输入图像不会被修改;利用.ptr和数组下标进行图像像素遍历
void colorReduce4(const Mat &image, Mat &result,int div = 64)
{
    int nl = image.rows;
    int nc = image.cols * image.channels();

    result.create(image.rows,image.cols,image.type());

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        const uchar *data_in = image.ptr<uchar>(j);
        uchar *data_out = result.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            data_out[i] = data_in[i]/div*div+div/2;     //减少图像中颜色总数的关键算法:if div = 64, then the total number of colors is 4x4x4;整数除法时,是向下取整。
        }
    }
}

//利用.ptr和数组下标进行图像像素遍历,并将nc放入for循环中(比较糟糕的做法)
void colorReduce5(Mat &image, int div = 64)
{
    int nl = image.rows;

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<image.cols * image.channels(); ++i)
        {
            data[i] = data[i]/div*div+div/2;     //减少图像中颜色总数的关键算法:if div = 64, then the total number of colors is 4x4x4;整数除法时,是向下取整。
        }
    }
}

//利用迭代器 cv::Mat iterator 进行图像像素遍历
void colorReduce6(Mat &image, int div = 64)
{
    Mat_<Vec3b>::iterator it = image.begin<Vec3b>();    //由于利用图像迭代器处理图像像素,因此返回类型必须在编译时知道
    Mat_<Vec3b>::iterator itend = image.end<Vec3b>();

    for(;it != itend; ++it)
    {
        (*it)[0] = (*it)[0]/div*div+div/2;        //利用operator[]处理每个通道的像素
        (*it)[1] = (*it)[1]/div*div+div/2;
        (*it)[2] = (*it)[2]/div*div+div/2;
    }
}

//利用.at<cv::Vec3b>(j,i)进行图像像素遍历
void colorReduce7(cv::Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols;

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        for(int i=0; i<nc; ++i)
        {
            image.at<cv::Vec3b>(j,i)[0] = image.at<cv::Vec3b>(j,i)[0]/div*div + div/2;
            image.at<cv::Vec3b>(j,i)[1] = image.at<cv::Vec3b>(j,i)[1]/div*div + div/2;
            image.at<cv::Vec3b>(j,i)[2] = image.at<cv::Vec3b>(j,i)[2]/div*div + div/2;
        }
    }
}

//减少循环次数,进行图像像素遍历,调用函数较少,效率最高。
void colorReduce8(cv::Mat &image, int div = 64)
{
    int nl = image.rows;
    int nc = image.cols;

    //判断是否是连续图像,即是否有像素填充
    if(image.isContinuous())
    {
        nc = nc*nl;
        nl = 1;
    }

    int n = static_cast<int>(log(static_cast<double>(div))/log(2.0));
    uchar mask = 0xFF<<n;

    //遍历图像的每个像素
    for(int j=0; j<nl ;++j)
    {
        uchar *data = image.ptr<uchar>(j);
        for(int i=0; i<nc; ++i)
        {
            *data++ = *data & mask +div/2;
            *data++ = *data & mask +div/2;
            *data++ = *data & mask +div/2;
        }
    }
}

const int NumTests = 9;        //测试算法的数量
const int NumIteration = 10;   //迭代次数

int main(int argc, char* argv[])
{

    char path[] = "/home/todayac/Desktop/img/test1.jpg";
    int64 t[NumTests],tinit;
    Mat image1;
    Mat image2;

    //数组初始化
    int i=0;
    while(i<NumTests)
    {
        t[i++] = 0;
    }

    int n = NumIteration;

    //迭代n次,取平均数
    for(int i=0; i<n; ++i)
    {
        image1 = imread(path);

        if(!image1.data)
        {
            cout<<"read image failue!"<<endl;
            return -1;
        }

        // using .ptr and []
        tinit = getTickCount();
        colorReduce0(image1);
        t[0] += getTickCount() - tinit;

        // using .ptr and *++
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce1(image1);
        t[1] += getTickCount() - tinit;

        // using .ptr and [] and modulo
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce2(image1);
        t[2] += getTickCount()  - tinit;

        // using .ptr and *++ and bitwise
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce3(image1);
        t[3] += getTickCount()  - tinit;

        //using input and output image
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce4(image1,image2);
        t[4] += getTickCount()  - tinit;

        // using .ptr and [] with image.cols * image.channels()
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce5(image1);
        t[5] += getTickCount()  - tinit;

        // using .ptr and *++ and iterator
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce6(image1);
        t[6] += getTickCount()  - tinit;

        //using at
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce7(image1);
        t[7] += getTickCount()  - tinit;

        //using .ptr and * ++ and bitwise (continuous+channels)
        image1 = imread(path);
        tinit = getTickCount();
        colorReduce8(image1);
        t[8] += getTickCount()  - tinit;
    }

    namedWindow("Result");
    imshow("Result",image1);
    namedWindow("Result Image");
    imshow("Result Image",image2);
    imwrite("/home/todayac/Desktop/img/test31.jpg",image1);
    imwrite("/home/todayac/Desktop/img/test41.jpg",image2);


    cout<<endl<<"-------------------------------------------------------------------------"<<endl<<endl;
    cout<<"using .ptr and [] = "<<1000*t[0]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and *++ = "<<1000*t[1]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and [] and modulo = "<<1000*t[2]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and *++ and bitwise = "<<1000*t[3]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using input and output image = "<<1000*t[4]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and [] with image.cols * image.channels() = "<<1000*t[5]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and *++ and iterator = "<<1000*t[6]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using at = "<<1000*t[7]/getTickFrequency()/n<<"ms"<<endl;
    cout<<"using .ptr and * ++ and bitwise (continuous+channels) = "<<1000*t[8]/getTickFrequency()/n<<"ms"<<endl;
    cout<<endl<<"-------------------------------------------------------------------------"<<endl<<endl;
    waitKey();
    return 0;
}








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值