opencv学习

目录

入门案列:

制作一张PNG格式的图片并保存至项目目录

 简单的图像混合

 滑动条:trackbar

 响应鼠标事件

Mat类

 基本数据类型

 图像绘制

颜色空间缩减(Look up table)

计时函数

削减图像--访问每个像素的方法

ROI(region of intresting) 感兴趣的区域

 split 和 merge

图像对比度和亮度通过滑动条变化


入门案列:

  cpp文件:

#include 
#include 
#include 
#include

#define ERODE 1
#define BLUR 2
#define CANNY 3
#define VIDEOCAPTURE 4
using namespace cv;
//erode image & blur image &  CANNY(edge detection) & videocapture
int main()
{
    int cmd =0;
    std::cout<<"1. erode \n2. blur\n3. canny(edge detection)\n4. VideoCapture"<>cmd;
    if (ERODE == cmd)   //erode image
    {
        //original image
        Mat srcImage = imread("Lark20200722110712.png");
        imshow("[original image erode operation]",srcImage);
        //set erode element
        Mat element = getStructuringElement(MORPH_RECT,Size(10,10));
        Mat dsImage;

        //erode image ...
        erode(srcImage,dsImage,element);
        //show image eroded
        imshow("[show image] erode image ",dsImage);
        waitKey(0);
    }else if(BLUR == cmd)   //blur image
    {
        Mat srcImage = imread("Lark20200722110712.png");
        imshow("[average filtering] original image",srcImage);

        Mat dstImage;

        blur(srcImage,dstImage,Size(7,7));
        imshow("[average filtering] design sketch",dstImage);
        waitKey(0);
    }else if(CANNY == cmd)
    {
       Mat srcImage = imread("Lark20200722110712.png");
       imshow("[edge detection] original image",srcImage);

       Mat dstImage,edge,grayImage;
       //create a matrix of the same type and size as src
       dstImage.create(srcImage.size(),srcImage.type());
       //convert the original image to grayscale
       cvtColor(srcImage,grayImage,COLOR_BGR2GRAY);
       //denoise -- use the kernel with 3*3 for noise reduction
       blur(grayImage,edge,Size(3,3));
       //run canny operator
       Canny(edge,edge,3,9,3);
       imshow("[edge detection]design sketch",edge);
       waitKey(0);
    }else if(VIDEOCAPTURE == cmd)
    {
        VideoCapture capture(0);
        Mat edges;
        while(1)
        {
            Mat frame;
            capture >> frame;
            cvtColor(frame,edges,COLOR_BGR2GRAY);
            blur(edges,edges,Size(7,7));
            Canny(edges,edges,0,30,3);
            imshow("Read the image of each frame",edges);
            if(waitKey(30)>=0)break;
        }
    }else
    {
        std::cout<<"cmd error!"<

 QT的pro导入文件:

DEPENDPATH += /usr/local/include/opencv4
DEPENDPATH += /usr/local/include

LIBS += -L /usr/local/lib/ -lopencv_core
LIBS += -L /usr/local/lib/ -lopencv_highgui
LIBS += -L /usr/local/lib/ -lopencv_imgcodecs
LIBS += -L /usr/local/lib/ -lopencv_imgproc
LIBS += -L /usr/local/lib/ -lopencv_videoio

制作一张PNG格式的图片并保存至项目目录

#include 
#include 
#include 
using namespace std;
using namespace cv;
void createAlphamat(Mat &mat)
{
    for(int i=0;i(i,j);
            rgba[0] = UCHAR_MAX;
            rgba[1] = saturate_cast((float(mat.cols - j)) / (static_cast(mat.cols)) * UCHAR_MAX);
            rgba[2] = saturate_cast((float(mat.rows - i)) / (static_cast(mat.rows)) * UCHAR_MAX);
            rgba[3] = saturate_cast(0.5 * (rgba[1] + rgba[2]));
        }
    }
}
int main()
{
    Mat mat(480,640,CV_8UC4);
    createAlphamat(mat);

    vector compression_params;
    compression_params.push_back(IMWRITE_PNG_COMPRESSION);
    compression_params.push_back(9);
    try
    {
        imwrite("transparent Alpha .png",mat,compression_params);
        imshow("PNG",mat);
        fprintf(stdout,"save PNG successfully!");
        waitKey(0);
    } catch (runtime_error &ex)
    {
        fprintf(stderr,"translate PNG error:%s\n",ex.what());
        return 1;
    }
    return 0;
}

 简单的图像混合

#include 
#include 
#include 
using namespace cv;

int main()
{
    Mat alpha1 = imread("Alpha1.png");
    namedWindow("Alpha1");
    imshow("Alpha1",alpha1);

    Mat image = imread("Alpha2.png",2|4);
    Mat logo = imread("Alpha3.png");
    namedWindow("Alpha2");
    imshow("Alpha2",image);

    namedWindow("[3]");
    imshow("[3]",logo);

    Mat imageROI;
    imageROI = image(Rect(0,0,logo.cols,logo.rows));
    //imageROI = image(Range(300,300+logo.rows),Range(500,500+logo.cols));

    addWeighted(imageROI,0.5,logo,0.3,0.,imageROI);
    namedWindow("[4]+logo");
    imshow("[4]+logo",image);
    imwrite("imwrite.jpg",image);
    waitKey();
    return 0;
}

 滑动条:trackbar

#include 
#include 
using namespace cv;
using namespace std;
#define WINDOW_NAME "Example of linear mixing"
const int g_nMaxAlphaValue = 100;
static int g_nAlphaValueSlider;
static double g_dAlphaValue;
static double g_dBetaValue;
static char TrackbarName[50];
static Mat g_srcImage1;
static Mat g_srcImage2;
static Mat g_dstImage;
void on_Trackbar(int ,void *)
{
    g_dAlphaValue = static_cast(g_nAlphaValueSlider / g_nMaxAlphaValue);
    g_dBetaValue = (1.0 - g_dAlphaValue);
    addWeighted(g_srcImage1,g_dAlphaValue,g_srcImage2,g_dBetaValue,0.0,g_dstImage);
    cout<<"current trackbar position: "<

 响应鼠标事件

#include 
#include 
using namespace cv;
using namespace std;
#define WINDOW_NAME "window"
void on_MouseHandle(int event , int x , int y , int flag,
                    void * param);
void DrawRectangle(Mat &img,Rect box);
void ShowHelpText();
static Rect g_rectangle;
static bool g_bDrawingBox = false ;
static RNG g_rng(static_cast(time(nullptr)));
int main()
{
    Mat srcImage(600,800,CV_8UC3), tempImage;
    srcImage.copyTo(tempImage);
    g_rectangle = Rect(-1,-1,0,0);
    srcImage = Scalar::all(0);
    namedWindow(WINDOW_NAME);
    setMouseCallback(WINDOW_NAME,on_MouseHandle,static_cast(&srcImage));
    while(1)
    {
        srcImage.copyTo(tempImage);
        if(g_bDrawingBox)
            DrawRectangle(tempImage,g_rectangle);
        imshow(WINDOW_NAME,tempImage);
        if(waitKey(10) == 27) //"EXC" key
            break;
    }
    return 0;
}
void on_MouseHandle(int event , int x, int y ,
                    int flag,void *param)
{
    Mat &image = *(static_cast(param));
    switch (event)
    {
        case EVENT_MOUSEMOVE:
        {
            if(g_bDrawingBox)
            {
                g_rectangle.width = x - g_rectangle.x;
                g_rectangle.height = y - g_rectangle.y;

            }
        }
        break;
        case EVENT_LBUTTONDOWN:
        {
            g_bDrawingBox = true;
            g_rectangle = Rect(x,y,0,0);
        }
        break;
        case EVENT_LBUTTONUP:
        {
            g_bDrawingBox = false;
            if(g_rectangle.width < 0)
            {
                g_rectangle.x += g_rectangle.width;
                g_rectangle.width *= -1;
            }
            if(g_rectangle.height < 0)
            {
                g_rectangle.y += g_rectangle.height;
                g_rectangle.height *= -1;
            }
            DrawRectangle(image,g_rectangle);
        }
        break;
    }
}
void DrawRectangle(Mat &img,Rect box)
{
    rectangle(img,box.tl(),box.br(),Scalar(g_rng.uniform(0,255),
                                  g_rng.uniform(0,255),
                                  g_rng.uniform(0,255)));
}

Mat类

#include 
#include 
using namespace std;
using namespace cv;
int main()
{
    Mat A,C;
    A = imread("Alpha1.png",IMREAD_ANYCOLOR|IMREAD_ANYDEPTH);
    Mat B(A);
    C = A;

    Mat D_ROI(A,Rect(10,10,100,100)); //rect
    Mat ROI = A(Range::all(),Range(1,3)); // rows , cols

    Mat F = A.clone();
    Mat G;
    A.copyTo(G);
    // create a Mat object
    //1
    Mat M(2,2,CV_8UC3,Scalar(0,0,255));
    cout <<"M = "<(3,3) << 0,-1,0,-1,5,-1,0,-1,0);
    cout <<"H = "<

 基本数据类型

#include 
#include 
#include 
using namespace std;
using namespace cv;

int main()
{
    //Point & vector
    Point2f p(6,2);
    cout << "two degrees point p = " << p <<" ;" << endl << endl;

    Point3f p3f(8,2,0);
    cout << "three degrees point p = " << p3f <<" ;" << endl << endl;

    vector v;
    v.push_back(3);
    v.push_back(5);
    v.push_back(7);
    cout << "shortvec = " << Mat(v) <<" ;" << endl << endl;

    vector points(20);
    for(size_t i = 0; i < points.size() ; ++i)
    {
        putchar(10);
        points[i] = Point2f(static_cast(i * 5) , static_cast(i % 7));
        cout << "two degrees point p = " << points <<" ;" ;
    }
    putchar(10);

    /*
     * typedef Point_ Point2i
     * typedef Point2i Point;
     * typedef Point_ Point2f
     */
    Point point ;
    point.x = 10;
    point.y = 8;
    //or
    Point point_1 = Point(10,8);

    //Scalar
    Scalar(10,0,255);

    //Size
    /*
     * typedef Size_ Size2i
     * typedef Size2i Size
     */
    Size(5,5);

    //Rect
    Rect rect(10,20,30,50),rect1(10,20,30,60),rect2(10,50,30,20),rect3;
    rect.tl(); // top-left point
    rect.br(); // bottom-right point
    rect.area();
    rect.size();
    bool b = rect.contains(Point(5,2));

    rect3 = rect1 & rect2;
    Rect (rect1 | rect2) ;

    Rect rectShift = rect + point;  //translation
    Rect rectScale = rect + Size(20,3); //Scale

    //cvColor()
    Mat srcImage = imread("Alpha1.png",2|4);
    Mat dstImage ;
    namedWindow("srcImage");
    imshow("srcImage",srcImage);
    cvtColor(srcImage , dstImage , COLOR_RGB2Luv);
    imshow("dstImage",dstImage);
    waitKey();
    
    //Vec
    /*
     * typedef Vec Vec2b
     */
    
    //function of prevent memory overflow
    //alignPtr   alignSize , allocate , deallocate , fasMalloc , fastFree
    
    // 
     *
     * fastAtan2() -- calculate vector angle
     * cubeRoot() -- calculate cube root
     * cvCeil() -- round up
     * cvFloor -- round down
     * cvRound -- rounding
     * ...
     *
    return 0;
}

 图像绘制

#include 
#include 
#define WINDOW_WIDTH 600
using namespace std;
using namespace cv;

int main()
{
    //init
    int thickness = 5;
    int lineType = 20;
    Mat image(480,500,CV_8UC3) ;

    //ellipse(...)
    ellipse(image,
            Point(WINDOW_WIDTH / 6
                        , WINDOW_WIDTH / 2),
            Size(WINDOW_WIDTH/4
                 , WINDOW_WIDTH/16),
            90.0,
            0,
            360,
            Scalar(255 , 50 , 50),
            -1,
            lineType);

    //circle(...)
    thickness = 2;
    lineType = 18;
    Point center(100,100);
    circle(image,
           center,
           WINDOW_WIDTH/32,
           Scalar(100,5,60),
           thickness,
           lineType);

    //fillPoly(...) -- polygon
    lineType = 18;
    Point rookPoints[1][20];
    rookPoints[0][0] = Point(WINDOW_WIDTH/4,
                             7*WINDOW_WIDTH/8);
    rookPoints[0][1] = Point(3*WINDOW_WIDTH/4,
                            7*WINDOW_WIDTH/8);
    rookPoints[0][2] = Point(3*WINDOW_WIDTH/4,
                             13*WINDOW_WIDTH/16);
    rookPoints[0][3] = Point(11*WINDOW_WIDTH/16,
                             13*WINDOW_WIDTH/16);
    rookPoints[0][4] = Point(19*WINDOW_WIDTH/32,
                             3*WINDOW_WIDTH/8);
    rookPoints[0][5] = Point(3*WINDOW_WIDTH/4,
                             3*WINDOW_WIDTH/8);
    rookPoints[0][6] = Point(3*WINDOW_WIDTH/4,
                            WINDOW_WIDTH/8);
    rookPoints[0][7] = Point(26*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/8);
    rookPoints[0][8] = Point(26*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/4);
    rookPoints[0][9] = Point(22*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/4);
    rookPoints[0][10] = Point(22*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/8);
    rookPoints[0][11] = Point(18*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/8);
    rookPoints[0][12] = Point(18*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/4);
    rookPoints[0][13] = Point(14*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/4);
    rookPoints[0][14] = Point(14*WINDOW_WIDTH/40,
                             WINDOW_WIDTH/8);
    rookPoints[0][15] = Point(WINDOW_WIDTH/4,
                             WINDOW_WIDTH/8);
    rookPoints[0][16] = Point(WINDOW_WIDTH/4,
                             3*WINDOW_WIDTH/8);
    rookPoints[0][17] = Point(13*WINDOW_WIDTH/32,
                             3*WINDOW_WIDTH/8);
    rookPoints[0][18] = Point(5*WINDOW_WIDTH/16,
                             13*WINDOW_WIDTH/16);
    rookPoints[0][19] = Point(WINDOW_WIDTH/4,
                             13*WINDOW_WIDTH/16);
    const Point* ppt[1] = {(rookPoints[0])};
    int npt[] = {20};
    fillPoly(image,
             ppt,
             npt,
             1,
             Scalar(56,212,85),
             lineType);

    //line(...) -- draw line
    thickness = 2;
    lineType = 18;
    Point start(WINDOW_WIDTH/9,WINDOW_WIDTH/2);
    Point end(WINDOW_WIDTH/9+30,WINDOW_WIDTH/2+20);
    line(image,
         start,
         end,
         Scalar(20,30,56),
         thickness,
         lineType
         );

    //rectangle(...) -- rect
    thickness= -1;
    lineType = 18;
    rectangle(image,
              Point(0,0),
              Point(30,30),
              Scalar(255,255,65),
              thickness,
              lineType
              );

    namedWindow("canvas",WINDOW_FULLSCREEN);
    imshow("canvas",image);
    waitKey();
    return 0;
}

颜色空间缩减(Look up table)

#include 
#include 
using namespace std;
using namespace cv;
static RNG rng(static_cast(time(nullptr)));
int main()
{
    int divideWith = 10;
    uchar table[256];
    for (int i=0;i<256;++i) {
        table[i] = static_cast(divideWith * (i/10));
    }
    Mat lookupTable(1,256,CV_8U);
    uchar *p = lookupTable.data;
    for (int i =0 ;i<256;++i) {
        p[i] = table[i];
    }
    Mat in(5,5,CV_8UC3);
    for (int i = 0;i(i,j);
            rgb[0] = static_cast(rng.uniform(0,255));
            rgb[1] = static_cast(rng.uniform(0,255));
            rgb[2] = static_cast(rng.uniform(0,255));
        }
    }
    Mat out(5,5,CV_8UC3);
    LUT(in,lookupTable,out);
    cout<<"Mat = "<

计时函数

    double time0 = static_cast(getTickCount());

    for (int i=0;i<10000;++i) {
        i = i+1;
    }

    time0 = (static_cast(getTickCount()) - time0)/ getTickFrequency();

    cout<<"run time = "<

 

削减图像--访问每个像素的方法

#include 
#include 
#include 
using namespace std;
using namespace cv;
void colorReduce(Mat &inoutImage , Mat &outputImage , int div);
int main()
{
    Mat srcImage = imread("/home/solitary/Pictures/1.png");
    if(!srcImage.data)
    {
        cout<<"image is not exist!"<(getTickCount());
    colorReduce(srcImage,dstImage,32);
    time0 = (static_cast(getTickCount()) - time0) / getTickFrequency();
    cout << "run time = " << time0 <(i);
        //*data++ =static_cast(*data / div * div + div + 2);
        for (int j = 0;j( data[j] / div * div + div / 2 );
        }
    }
}
//2 look up table  run time = 0.000743581
void colorReduce2(Mat &inputImage ,Mat &outputImage , int div)
{
    //inputImage.copyTo(outputImage);
    outputImage = inputImage.clone();
    uchar table[256] ;
    for (int i = 0 ;i < 256;++i)
    {
        table[i] =static_cast(i / div * div + div / 2);
    }
    Mat lookUpTable(1,256,CV_8U);
    uchar *p = lookUpTable.data;
    for (int i=0;i<256;++i)
    {
        p[i] = table[i];
    }
    LUT(inputImage,lookUpTable,outputImage);
}
//3 iterator    run time = 0.0139368
void colorReduce3(Mat &inputImage ,Mat &outputImage , int div)
{
    inputImage.copyTo(outputImage);
    Mat_::iterator it;
    //iterator
    Mat_::iterator itBegin = outputImage.begin();
    Mat_::iterator itEnd = outputImage.end();

    for (it = itBegin;it != itEnd;++it)
    {
        //B
        (*it)[0] =static_cast((*it)[0] / div * div + div / 2);
        //G
        (*it)[1] =static_cast((*it)[1] / div * div + div / 2);
        //R
        (*it)[2] =static_cast((*it)[2] / div * div + div / 2);
    }
}
//4 dynamic address calculation  run time = 0.0159052
void colorReduce(Mat &inputImage ,Mat &outputImage , int div)
{
    outputImage = inputImage.clone();
    int rowNumber = outputImage.rows;
    int colNumber = outputImage.cols;

    for (int i=0;i(i,j)[0] = static_cast(
                    outputImage.at(i,j)[0] / div * div + div / 2);
            //G
            outputImage.at(i,j)[1] = static_cast(
                    outputImage.at(i,j)[1] / div * div + div / 2);
            //R
            outputImage.at(i,j)[2] = static_cast(
                    outputImage.at(i,j)[2] / div * div + div / 2);
        }
    }
}

ROI(region of intresting) 感兴趣的区域

int main()
{
    string imageName1 = IMAGEURL;
    imageName1.append("1.png");
    string imageName2 = IMAGEURL;
    imageName2.append("3.png");

    Mat srcImage = imread(imageName1);
    Mat logo = imread(imageName2);
    if(!srcImage.data || !logo.data)
    {
        cout<<"image is not exist"<

 split 和 merge

#include 
#include 
#include 
using namespace std;
using namespace cv;

int main()
{
    vector channels;
    Mat imageBlueChannel;
    Mat imageGreenChannel;
    Mat imageRedChannel;

    Mat mergeImage;
    Mat srcImage = imread("/home/solitary/Pictures/1.png");
    //split
    split(srcImage , channels);
    
    imageBlueChannel = channels.at(0);
    imageGreenChannel = channels.at(1);
    imageRedChannel = channels.at(2);
    //merge
    merge(channels,mergeImage);

    imshow("mergeImage",mergeImage);
    waitKey(0);
    return 0;
}

图像对比度和亮度通过滑动条变化

#include 
#include 
#include 
using namespace std;
using namespace cv;

static void on_ContrastAndBright(int , void *);
static void ShowHelpText();

static int g_nContrastValue;
static int g_nBrightValue;
Mat g_srcImage,g_dstImage;
int main()
{
    g_srcImage = imread("/home/solitary/Pictures/1.png");
    if(!g_srcImage.data)
    {
        cout<<"image isn't exist"<((g_nContrastValue*0.01)*i + g_nBrightValue);
//    }
//    uchar *p = lookUpTable.data;
//    for (int i=0;i<256;++i)
//    {
//        p[i] = table[i];
//    }
//    LUT(g_srcImage , lookUpTable , g_dstImage);
    for (int i = 0 ; i(i,j)[c] =
                        saturate_cast((g_nContrastValue*0.01)
                                             *(g_srcImage.at(i,j)[c])
                                             + g_nBrightValue);
            }
        }
    }

    imshow("original window",g_srcImage);
    imshow("window",g_dstImage);
    waitKey(0);
}

 

你可能感兴趣的:(opencv,c++)