A few simple OpenCV programs

OpenCV official website: https://opencv.org/

Baidu Encyclopedia

OpenCV is a cross-platform computer vision library released under the BSD license (open source) and can run on Linux, Windows, Android and Mac OS operating systems. It is lightweight and efficient - it consists of a series of C functions and a small number of C++ classes, and provides interfaces to languages ​​such as Python, Ruby, and MATLAB, and implements many general algorithms in image processing and computer vision.

OpenCV is written in C++ language, and its main interface is also C++ language, but still retains a large number of C language interfaces. The library also has extensive Python, Java and MATLAB/OCTAVE (version 2.5) interfaces. The API interface functions of these languages ​​can be obtained through the online documentation. Now also provides support for C#, Ch, Ruby.

All new developments and algorithms are interfaced with C++. A GPU interface using CUDA was also implemented in September 2010.

The following are reproduced several OpenCV programs.

my environment:

$ pkg-config --modversion opencv
2.4.13
$ uname -a
Linux toa 3.10.0-693.17.1.el7.x86_64 #1 SMP Thu Jan 25 20:13:58 UTC 2018 x86_64 x86_64 x86_64 GNU/Linux
$ g++ --version
g++ (GCC) 4.8.5 20150623 (Red Hat 4.8.5-16)

1. Display pictures https://www.cnblogs.com/Crysaty/p/6638152.html

#include <highgui.h>  
   
int main(int argc,char ** argv)
{  
    IplImage* img = cvLoadImage(argv[1],CV_LOAD_IMAGE_COLOR);  
    cvNamedWindow("Image_show",CV_WINDOW_AUTOSIZE);  
    cvShowImage("Image_show",img);  
    cvWaitKey(0);  
    cvReleaseImage(&img);  
    cvDestroyWindow("Image_show");  
     return 0;  
}

Compile and run:

$ make
gcc main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../windows.png

Effect picture (left), original picture (right):


A C++ code:

#include <opencv2/opencv.hpp>
#include <iostream>
using namespace std;
using namespace cv;
int main(int argc, char **argv)  
{  

    Mat imggray=imread(argv[1],CV_LOAD_IMAGE_COLOR);  
    cvtColor(imggray,imggray,CV_RGB2GRAY);//RGB2GRAY
    imshow("123",imggray);//Show pictures  
    waitKey(0);
    return 1;
}

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../wongrgb.jpg

2. Binary map + contour map https://www.cnblogs.com/always-chang/p/6170859.html

#include <opencv2/opencv.hpp>  
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")  
IplImage *g_pGrayImage = NULL;
const char *pstrWindowsBinaryTitle = "Binary Image";
const char *pstrWindowsOutLineTitle = "Outline";
CvSeq *g_pcvSeq = NULL;

void on_trackbar(int pos)
{
    // Convert to binary image  
    IplImage *pBinaryImage = cvCreateImage(cvGetSize(g_pGrayImage), IPL_DEPTH_8U, 1);
    cvThreshold(g_pGrayImage, pBinaryImage, pos, 255, CV_THRESH_BINARY);
    // display the binary image  
    cvShowImage(pstrWindowsBinaryTitle, pBinaryImage);

    CvMemStorage* cvMStorage = cvCreateMemStorage();
    // Retrieve contours and return the number of detected contours  
    cvFindContours(pBinaryImage, cvMStorage, &g_pcvSeq);

    IplImage *pOutlineImage = cvCreateImage(cvGetSize(g_pGrayImage), IPL_DEPTH_8U, 3);
    int _levels = 5;
    cvZero(pOutlineImage);
    cvDrawContours(pOutlineImage, g_pcvSeq, CV_RGB(255, 0, 0), CV_RGB(0, 255, 0), _levels);
    cvShowImage(pstrWindowsOutLineTitle, pOutlineImage);

    cvReleaseMemStorage(&cvMStorage);
    cvReleaseImage(&pBinaryImage);
    cvReleaseImage(&pOutlineImage);
}

int main(int argc, char** argv)
{
    const char *pstrWindowsSrcTitle = "Original Image";
    const char *pstrWindowsToolBarName = "Binarize";

    // Load the original image from the file  
    IplImage *pSrcImage = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
    // show original image  
    cvNamedWindow(pstrWindowsSrcTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsSrcTitle, pSrcImage);

    // convert to grayscale  
    g_pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
    cvCvtColor(pSrcImage, g_pGrayImage, CV_BGR2GRAY);

    // Create binary and contour plot windows  
    cvNamedWindow(pstrWindowsBinaryTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsOutLineTitle, CV_WINDOW_AUTOSIZE);


    // slider    
    int nThreshold = 0;
    cvCreateTrackbar(pstrWindowsToolBarName, pstrWindowsBinaryTitle, &nThreshold, 254, on_trackbar);

    on_trackbar(1);

    cvWaitKey(0);

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

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../wong.jpg

Effect picture:



3. Mouse drawing https://www.cnblogs.com/always-chang/p/6170859.html

#include <opencv2/opencv.hpp>  
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")  
const char *pstrWindowsMouseDrawTitle = "Mouse drawing";
// callback function for mouse message  
void on_mouse(int event, int x, int y, int flags, void* param)
{
    static bool s_bMouseLButtonDown = false;
    static CvPoint s_cvPrePoint = cvPoint(0, 0);

    switch (event)
    {
    case CV_EVENT_LBUTTONDOWN:
        s_bMouseLButtonDown = true;
        s_cvPrePoint = cvPoint(x, y);
        break;

    case  CV_EVENT_LBUTTONUP:
        s_bMouseLButtonDown = false;
        break;

    case CV_EVENT_MOUSEMOVE:
        if (s_bMouseLButtonDown)
        {
            CvPoint cvCurrPoint = cvPoint(x, y);
            cvLine((IplImage*)param, s_cvPrePoint, cvCurrPoint, CV_RGB(0, 0, 20), 3);
            s_cvPrePoint = cvCurrPoint;
            cvShowImage(pstrWindowsMouseDrawTitle, (IplImage*)param);
        }
        break;
    }
}
intmain()
{
    const int MAX_WIDTH = 500, MAX_HEIGHT = 400;
    const char *pstrSaveImageName = "Draw.jpg";

    IplImage *pSrcImage = cvCreateImage(cvSize(MAX_WIDTH, MAX_HEIGHT), IPL_DEPTH_8U, 3);
    cvSet(pSrcImage, CV_RGB(255, 255, 255)); //You can use cvSet() to fill the image with white  
    cvNamedWindow(pstrWindowsMouseDrawTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsMouseDrawTitle, pSrcImage);

    cvSetMouseCallback(pstrWindowsMouseDrawTitle, on_mouse, (void*)pSrcImage);

    int c;
    do{
        c = cvWaitKey(0);
        switch ((char)c)
        {
        case 'r'://rRedraw
            cvSet(pSrcImage, CV_RGB(255, 255, 255));
            cvShowImage(pstrWindowsMouseDrawTitle, pSrcImage);
            break;

        case 's'://s save image
            cvSaveImage(pstrSaveImageName, pSrcImage);
            break;
        }
    } while (c > 0 && c != 27);

    cvDestroyWindow(pstrWindowsMouseDrawTitle);
    cvReleaseImage(&pSrcImage);
    return 0;
}

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out

Effect picture:


4. Grayscale histogram https://www.cnblogs.com/always-chang/p/6170859.html

#include <opencv2/opencv.hpp>  
#include <opencv2/legacy/compat.hpp>  
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")  

void FillWhite(IplImage *pImage)
{
    cvRectangle(pImage, cvPoint(0, 0), cvPoint(pImage->width, pImage->height), CV_RGB(255, 255, 255), CV_FILLED);
}
// Create a histogram of the grayscale image  
CvHistogram* CreateGrayImageHist(IplImage **ppImage)
{
    int nHistSize = 256;
    float fRange[] = { 0, 255 }; // The range of gray levels    
    float *pfRanges[] = { fRange };
    CvHistogram *pcvHistogram = cvCreateHist(1, &nHistSize, CV_HIST_ARRAY, pfRanges);
    cvCalcHist(ppImage, pcvHistogram);
    return pcvHistogram;
}
// Create a histogram image from the histogram  
IplImage * CreateHisogramImage (int nImageWidth, int nScale, int nImageHeight, CvHistogram * pcvHistogram)
{
    IplImage * pHistImage = cvCreateImage (cvSize (nImageWidth * nScale, nImageHeight), IPL_DEPTH_8U, 1);
    FillWhite(pHistImage);

    //The largest block in the statistics histogram  
    float fMaxHistValue = 0;
    cvGetMinMaxHistValue(pcvHistogram, NULL, &fMaxHistValue, NULL, NULL);

    //Plot the value of each square to the graph separately  
    int i;
    for (i = 0; i < nImageWidth; i++)
    {
        float fHistValue = cvQueryHistValue_1D(pcvHistogram, i); //The size of the rectangle whose pixel is i  
        int nRealHeight = cvRound((fHistValue / fMaxHistValue) * nImageHeight); //height to draw  
        cvRectangle(pHistImage,
            cvPoint (i * nScale, nImageHeight - 1),
            cvPoint ((i + 1) * nScale - 1, nImageHeight - nRealHeight),
            cvScalar(i, 0, 0, 0),
            CV_FILLED
            );
    }
    return pHistImage;
}
int main(int argc, char** argv)
{
    const char *pstrWindowsSrcTitle = "Original Image";
    const char *pstrWindowsGrayTitle = "Grayscale";
    const char *pstrWindowsHistTitle = "Histogram";

    // Load the original image from the file  
    IplImage *pSrcImage = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
    IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
    // grayscale image  
    cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);

    // grayscale histogram  
    CvHistogram *pcvHistogram = CreateGrayImageHist(&pGrayImage);

    // create the histogram image  
    int nHistImageWidth = 255;
    int nHistImageHeight = 150; //Histogram image height  
    int nScale = 2;
    IplImage *pHistImage = CreateHisogramImage(nHistImageWidth, nScale, nHistImageHeight, pcvHistogram);

    // show  
    cvNamedWindow(pstrWindowsSrcTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsGrayTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsHistTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsSrcTitle, pSrcImage);
    cvShowImage(pstrWindowsGrayTitle, pGrayImage);
    cvShowImage(pstrWindowsHistTitle, pHistImage);

    cvWaitKey(0);

    cvReleaseHist(&pcvHistogram);

    cvDestroyWindow(pstrWindowsSrcTitle);
    cvDestroyWindow(pstrWindowsGrayTitle);
    cvDestroyWindow(pstrWindowsHistTitle);
    cvReleaseImage(&pSrcImage);
    cvReleaseImage(&pGrayImage);
    cvReleaseImage(&pHistImage);
    return 0;
}

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../wongrgb.jpg

Effect picture:


5. Grayscale histogram equalization

#include <opencv2/opencv.hpp>  
#include <opencv2/legacy/compat.hpp>  
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")  
void FillWhite(IplImage *pImage)
{
    cvRectangle(pImage, cvPoint(0, 0), cvPoint(pImage->width, pImage->height), CV_RGB(255, 255, 255), CV_FILLED);
}
// Create a histogram of the grayscale image  
CvHistogram* CreateGrayImageHist(IplImage **ppImage)
{
    int nHistSize = 256;
    float fRange[] = { 0, 255 }; // The range of gray levels    
    float *pfRanges[] = { fRange };
    CvHistogram *pcvHistogram = cvCreateHist(1, &nHistSize, CV_HIST_ARRAY, pfRanges);
    cvCalcHist(ppImage, pcvHistogram);
    return pcvHistogram;
}
// Create a histogram image from the histogram  
IplImage * CreateHisogramImage (int nImageWidth, int nScale, int nImageHeight, CvHistogram * pcvHistogram)
{
    IplImage * pHistImage = cvCreateImage (cvSize (nImageWidth * nScale, nImageHeight), IPL_DEPTH_8U, 1);
    FillWhite(pHistImage);

    //The largest block in the statistics histogram  
    float fMaxHistValue = 0;
    cvGetMinMaxHistValue(pcvHistogram, NULL, &fMaxHistValue, NULL, NULL);

    //Plot the value of each square to the graph separately  
    int i;
    for (i = 0; i < nImageWidth; i++)
    {
        float fHistValue = cvQueryHistValue_1D(pcvHistogram, i); //The size of the rectangle whose pixel is i  
        int nRealHeight = cvRound((fHistValue / fMaxHistValue) * nImageHeight); //height to draw  
        cvRectangle(pHistImage,
            cvPoint (i * nScale, nImageHeight - 1),
            cvPoint ((i + 1) * nScale - 1, nImageHeight - nRealHeight),
            cvScalar(i, 0, 0, 0),
            CV_FILLED
            );
    }
    return pHistImage;
}
int main(int argc, char** argv)
{
    const char *pstrWindowsSrcTitle = "Original Image";
    const char *pstrWindowsGrayTitle = "Grayscale";
    const char *pstrWindowsHistTitle = "Histogram";
    const char *pstrWindowsGrayEqualizeTitle = "Grayscale - After Equalization";
    const char *pstrWindowsHistEqualizeTitle = "Histogram-After Equalization";

    // Load the original image from the file  
    IplImage *pSrcImage = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
    IplImage *pGrayImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);
    IplImage *pGrayEqualizeImage = cvCreateImage(cvGetSize(pSrcImage), IPL_DEPTH_8U, 1);

    // grayscale image  
    cvCvtColor(pSrcImage, pGrayImage, CV_BGR2GRAY);
    // Histogram image data  
    int nHistImageWidth = 255;
    int nHistImageHeight = 150;
    int nScale = 2;

    // Grayscale histogram and histogram image  
    CvHistogram *pcvHistogram = CreateGrayImageHist(&pGrayImage);
    IplImage *pHistImage = CreateHisogramImage(nHistImageWidth, nScale, nHistImageHeight, pcvHistogram);

    // equalize  
    cvEqualizeHist(pGrayImage, pGrayEqualizeImage);

    // equalized grayscale histogram and histogram image  
    CvHistogram *pcvHistogramEqualize = CreateGrayImageHist(&pGrayEqualizeImage);
    IplImage *pHistEqualizeImage = CreateHisogramImage(nHistImageWidth, nScale, nHistImageHeight, pcvHistogramEqualize);


    // show
    cvNamedWindow(pstrWindowsGrayTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsHistTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsGrayEqualizeTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsHistEqualizeTitle, CV_WINDOW_AUTOSIZE);
    //display code....
    cvShowImage(pstrWindowsGrayTitle, pGrayImage);//Show grayscale image
    cvShowImage(pstrWindowsHistTitle, pHistImage);//Display grayscale histogram
    cvShowImage(pstrWindowsGrayEqualizeTitle, pGrayEqualizeImage);//Display the equalized grayscale image
    cvShowImage(pstrWindowsHistEqualizeTitle, pHistEqualizeImage);//Display the equalized grayscale histogram

    //display code....
    cvWaitKey(0);

    //Recycle resource code...
    cvDestroyWindow(pstrWindowsGrayTitle);
    cvDestroyWindow(pstrWindowsHistTitle);
    cvDestroyWindow(pstrWindowsGrayEqualizeTitle);
    cvDestroyWindow(pstrWindowsHistEqualizeTitle);

    cvReleaseImage(&pSrcImage);
    cvReleaseImage(&pHistImage);
    cvReleaseImage(&pGrayEqualizeImage);
    cvReleaseImage(&pHistEqualizeImage);

    return 0;
}

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../wongrgb.jpg

Effect picture:


6. Color histogram equalization

#include <opencv2/opencv.hpp>  
using namespace std;
#pragma comment(linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"")  
//Histogram equalization of color images  
IplImage* EqualizeHistColorImage(IplImage *pImage)
{
    IplImage *pEquaImage = cvCreateImage(cvGetSize(pImage), pImage->depth, 3);

    // Divide the original image into each channel and then equalize, and finally merge the histogram equalization of the color image  
    const int MAX_CHANNEL = 4;
    IplImage *pImageChannel[MAX_CHANNEL] = { NULL };

    int i;
    for (i = 0; i < pImage->nChannels; i++)
        pImageChannel[i] = cvCreateImage(cvGetSize(pImage), pImage->depth, 1);

    cvSplit(pImage, pImageChannel[0], pImageChannel[1], pImageChannel[2], pImageChannel[3]);

    for (i = 0; i < pImage->nChannels; i++)
        cvEqualizeHist(pImageChannel[i], pImageChannel[i]);

    cvMerge(pImageChannel[0], pImageChannel[1], pImageChannel[2], pImageChannel[3], pEquaImage);

    for (i = 0; i < pImage->nChannels; i++)
        cvReleaseImage(&pImageChannel[i]);

    return pEquaImage;
}
int main(int argc, char** argv)
{
    const char *pstrWindowsSrcTitle = "Original Image";
    const char *pstrWindowsHisEquaTitle = "After histogram equalization";

    // Load the original image from the file  
    IplImage *pSrcImage = cvLoadImage(argv[1], CV_LOAD_IMAGE_UNCHANGED);
    IplImage *pHisEquaImage = EqualizeHistColorImage(pSrcImage);

    cvNamedWindow(pstrWindowsSrcTitle, CV_WINDOW_AUTOSIZE);
    cvNamedWindow(pstrWindowsHisEquaTitle, CV_WINDOW_AUTOSIZE);
    cvShowImage(pstrWindowsSrcTitle, pSrcImage);
    cvShowImage(pstrWindowsHisEquaTitle, pHisEquaImage);


    cvWaitKey(0);

    cvDestroyWindow(pstrWindowsSrcTitle);
    cvDestroyWindow(pstrWindowsHisEquaTitle);
    cvReleaseImage(&pSrcImage);
    cvReleaseImage(&pHisEquaImage);
    return 0;
}

Compile and run:

$ make
g++ main.c `pkg-config --cflags --libs opencv`
$ ./a.out ../wongrgb.jpg

Effect picture (the effect is not very good):



More operation examples: https://blog.csdn.net/qq_35874394/article/details/53290370

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325760798&siteId=291194637