qt下OpenCV编程例子笔记一

以下所有例子来源于http://wiki.opencv.org.cn

一、读入图片显示

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"

#if 1
using namespace cv;
int main() {
    //声明IplImage指针
    IplImage* pImg;
    //载入图片
    pImg=cvLoadImage("../Lena.jpg",CV_LOAD_IMAGE_COLOR);  //C:\2.jpg 要使用'/' 而不是windows的 '\'
    if(NULL==pImg)
    {
        printf("image can't read!\n");
        return -1;
    }
   // Mat image(pImg); //有这句话,为什么会出错
    //创建窗口
    //cvNamedWindow("Image",CV_WINDOW_AUTOSIZE);  // 为什么注释掉这句话,程序尼玛也运行
    //显示图像
    cvShowImage("Image",pImg);
    //等待按键
    cvWaitKey(0);
    //销毁窗口
    cvDestroyWindow("Image");
    //释放图像
    cvReleaseImage(&pImg);     // 为什么我把这条语句放在cvWaitKey前面时,窗口任然有图像显示,放在cvShowImage前面时才没有图片显示
    return 0;
}
#else
    #if 0
    using namespace cv; //下面函数要cv前缀
    int main()
    {
        Mat image;
        image=imread("C:/2.jpg");
        imshow("li",image);
        waitKey();
        return 0;
    }
    #else
    using namespace cv;//下面的所有cv相关类型不用加上前缀了,这里的前缀为cv::
    int main(int argc, char* argv[])
    {
        Mat img = imread("Lena.jpg"); //声明Mat变量并调入lena的照片,图片放在工程目录中直接使用"Lena.jpg"不行,要把图片放在工程目录的上一层
        //然后使用../Lena.jpg,对于使用vs的这使用..\\Lena.jpg,第一个\为转义字符

        if(!img.data) //判断图片调入是否成功
             return -1; //调入图片失败则退出
        //创建窗口,并确定其为大小不可变类型窗口
        namedWindow("loveLena", CV_WINDOW_AUTOSIZE);

        //显示图片。如果你不介意窗口大小可变,可以直接注释掉上一句。因为imshow可以直接创建窗口
        imshow("loveLena", img);

        waitKey(); //等待按键

        return 0;
}

    #endif
#endif

二、图像创建、保存和复制

最终在工程目录上一级目录中生成copy.jpg

#include "cv.h"
#include "highgui.h"

int main( int argc, char** argv )
{
    IplImage* pImg; //声明IplImage指针

    //载入图像,强制转化为Gray
    pImg = cvLoadImage("../Lena.jpg", 0);
    if(pImg != NULL )
    {
      IplImage* pImg2 = cvCreateImage(cvGetSize(pImg),
                      pImg->depth,
                      pImg->nChannels);
      cvCopy(pImg, pImg2, NULL);

      cvSaveImage("../copy.jpg", pImg2);//把图像写入文件

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

      cvWaitKey(0); //等待按键

      cvDestroyWindow( "Image" );//销毁窗口
      cvReleaseImage( &pImg ); //释放图像
      cvReleaseImage( &pImg2 ); //释放图像
      return 0;
    }

  return -1;
}

三、canny边缘检测

重点函数:

cvCanny(pImg, pCannyImg, 50, 150, 3);

#include "cv.h"
#include "cxcore.h"
#include "highgui.h"

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

  //声明IplImage指针
  IplImage* pImg = NULL;
  IplImage* pCannyImg = NULL;

  //载入图像,强制转化为Gray
  pImg = cvLoadImage("../Lena.jpg", 0);

  if(pImg != NULL )

    {
      //为canny边缘图像申请空间
      pCannyImg = cvCreateImage(cvGetSize(pImg),
                      IPL_DEPTH_8U,
                      1);

      //canny边缘检测
      cvCanny(pImg, pCannyImg, 50, 150, 3);

      //创建窗口
      cvNamedWindow("src", 1);
      cvNamedWindow("canny",1);

      //显示图像
      cvShowImage( "src", pImg );
      cvShowImage( "canny", pCannyImg );
      cvWaitKey(0); //等待按键

      //销毁窗口
      cvDestroyWindow( "src" );
      cvDestroyWindow( "canny" );

      //释放图像
      cvReleaseImage( &pImg );
      cvReleaseImage( &pCannyImg );
      return 0;
    }

  return -1;
}

四、轮廓(contour)检测

#ifdef _CH_
#pragma package 
#endif

#ifndef _EiC
#include "cv.h"
#include "cxcore.h"
#include "highgui.h"
#include 

#endif
#define w 500
int levels = 3;
CvSeq* contours = 0;

void on_trackbar(int pos)

{
    IplImage* cnt_img = cvCreateImage( cvSize(w,w), 8, 3 );
    CvSeq* _contours = contours;
    int _levels = levels - 3;

    if( _levels <= 0 ) // get to the nearest face to make it look more funny

    _contours = _contours->h_next->h_next->h_next;
    cvZero( cnt_img );
    cvDrawContours( cnt_img, _contours, CV_RGB(255,0,0), CV_RGB(0,255,0), _levels, 3, CV_AA, cvPoint(0,0) );
    cvShowImage( "contours", cnt_img );
    cvReleaseImage( &cnt_img );
}

int main( int argc, char** argv )
{
    int i, j;
    CvMemStorage* storage = cvCreateMemStorage(0);
    IplImage* img = cvCreateImage( cvSize(w,w), 8, 1 );
    cvZero( img );

    for( i=0; i < 6; i++ )
    {
        int dx = (i%2)*250 - 30;
        int dy = (i/2)*150;
        CvScalar white = cvRealScalar(255);
        CvScalar black = cvRealScalar(0);

        if( i == 0 )
        {
            for( j = 0; j <= 10; j++ )
            {
                double angle = (j+5)*CV_PI/21;
                cvLine(img, cvPoint(cvRound(dx+100+j*10-80*cos(angle)),
                cvRound(dy+100-90*sin(angle))),
                cvPoint(cvRound(dx+100+j*10-30*cos(angle)),
                cvRound(dy+100-30*sin(angle))), white, 1, 8, 0);
            }
        }

        cvEllipse( img, cvPoint(dx+150, dy+100), cvSize(100,70), 0, 0, 360, white, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+115, dy+70), cvSize(30,20), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+185, dy+70), cvSize(30,20), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+115, dy+70), cvSize(15,15), 0, 0, 360, white, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+185, dy+70), cvSize(15,15), 0, 0, 360, white, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+115, dy+70), cvSize(5,5), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+185, dy+70), cvSize(5,5), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+150, dy+100), cvSize(10,5), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+150, dy+150), cvSize(40,10), 0, 0, 360, black, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+27, dy+100), cvSize(20,35), 0, 0, 360, white, -1, 8, 0 );
        cvEllipse( img, cvPoint(dx+273, dy+100), cvSize(20,35), 0, 0, 360, white, -1, 8, 0 );
    }

    cvNamedWindow( "image", 1 );
    cvShowImage( "image", img );

    cvFindContours( img, storage, &contours, sizeof(CvContour),
                    CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cvPoint(0,0) );

    // comment this out if you do not want approximation
    contours = cvApproxPoly( contours, sizeof(CvContour), storage, CV_POLY_APPROX_DP, 3, 1 );
    cvNamedWindow( "contours", 1 );
    cvCreateTrackbar( "levels+3", "contours", &levels, 7, on_trackbar );

    on_trackbar(0);
    cvWaitKey(0);
    cvReleaseMemStorage( &storage );
    cvReleaseImage( &img );
    return 0;

}
#ifdef _EiC
main(1,"");
#endif

五、图像旋转与缩放

//按Esc键退出
#include "cv.h"
#include "highgui.h"
#include "math.h"

int main (int argc, char **argv)
{
  IplImage *src = 0;
  IplImage *dst = 0;

  /* the first command line parameter must be image file name */
  src = cvLoadImage("../Lena.jpg", -1);

  if (src != 0)
    {
      int delta = 1;
      int angle = 0;
      int opt = 0;	// 1: 旋转加缩放
                        // 0:  仅仅旋转

      double factor;
      dst = cvCloneImage (src);
      cvNamedWindow ("src", 1);
      cvShowImage ("src", src);

        for (;;)
        {
          float m[6];

          // Matrix m looks like:
          //
          // [ m0  m1  m2 ] ===>  [ A11  A12   b1 ]
          // [ m3  m4  m5 ]       [ A21  A22   b2 ]
          //
          CvMat M = cvMat (2, 3, CV_32F, m);
          int w = src->width;
          int h = src->height;

          if (opt)		// 旋转加缩放
            factor = (cos (angle * CV_PI / 180.) + 1.0) * 2;
          else			//  仅仅旋转
            factor = 1;
          m[0] = (float) (factor * cos (-angle * 2 * CV_PI / 180.));
          m[1] = (float) (factor * sin (-angle * 2 * CV_PI / 180.));
          m[3] = -m[1];
          m[4] = m[0];

          // 将旋转中心移至图像中间
          m[2] = w * 0.5f;
          m[5] = h * 0.5f;

          //  dst(x,y) = A * src(x,y) + b
          cvZero (dst);
          cvGetQuadrangleSubPix (src, dst, &M);
          cvNamedWindow ("dst", 1);
          cvShowImage ("dst", dst);

          if (cvWaitKey (1) == 27)	//ESC
            break;
          angle = (int) (angle + delta) % 360;
        }			// for-loop
    }
  return 0;
}

六、读入视频文件及运动物体检测

#include 
#include 
#include 
#include 

int main( int argc, char** argv )
{
  //声明IplImage指针
  IplImage* pFrame = NULL;
  IplImage* pFrImg = NULL;
  IplImage* pBkImg = NULL;
  CvMat* pFrameMat = NULL;
  CvMat* pFrMat = NULL;
  CvMat* pBkMat = NULL;
  CvCapture* pCapture = NULL;
  int nFrmNum = 0;

  //创建窗口
  cvNamedWindow("video", 1);
  cvNamedWindow("background",1);
  cvNamedWindow("foreground",1);

  //使窗口有序排列
  cvMoveWindow("video", 30, 0);
  cvMoveWindow("background", 360, 0);
  cvMoveWindow("foreground", 690, 0);

 /*
  if( argc > 2 )
    {
      fprintf(stderr, "Usage: bkgrd [video_file_name]\n");
      return -1;
    }
 */

  //打开摄像头
 // if (argc ==1)
    if( !(pCapture = cvCaptureFromCAM(-1)))
      {
        fprintf(stderr, "Can not open camera.\n");
        return -2;
      }

  //打开视频文件
  /*
  if(argc == 2)
    if( !(pCapture = cvCaptureFromFile(argv[1])))
      {
        fprintf(stderr, "Can not open video file %s\n", argv[1]);
        return -2;
      }
 */

  //逐帧读取视频
  while(pFrame = cvQueryFrame( pCapture ))
    {
        nFrmNum++;
        //如果是第一帧,需要申请内存,并初始化
        if(nFrmNum == 1)
        {
          pBkImg = cvCreateImage(cvSize(pFrame->width, pFrame->height),  IPL_DEPTH_8U,1);
          pFrImg = cvCreateImage(cvSize(pFrame->width, pFrame->height),  IPL_DEPTH_8U,1);
          pBkMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);
          pFrMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);
          pFrameMat = cvCreateMat(pFrame->height, pFrame->width, CV_32FC1);

          //转化成单通道图像再处理
          cvCvtColor(pFrame, pBkImg, CV_BGR2GRAY);
          cvCvtColor(pFrame, pFrImg, CV_BGR2GRAY);
          cvConvert(pFrImg, pFrameMat);
          cvConvert(pFrImg, pFrMat);
          cvConvert(pFrImg, pBkMat);
        }
        else
        {
          cvCvtColor(pFrame, pFrImg, CV_BGR2GRAY);
          cvConvert(pFrImg, pFrameMat);
          //高斯滤波先,以平滑图像
          //cvSmooth(pFrameMat, pFrameMat, CV_GAUSSIAN, 3, 0, 0);
          //当前帧跟背景图相减
          cvAbsDiff(pFrameMat, pBkMat, pFrMat);

          //二值化前景图
          cvThreshold(pFrMat, pFrImg, 60, 255.0, CV_THRESH_BINARY);
          //进行形态学滤波,去掉噪音
          //cvErode(pFrImg, pFrImg, 0, 1);
          //cvDilate(pFrImg, pFrImg, 0, 1);

          //更新背景
          cvRunningAvg(pFrameMat, pBkMat, 0.003, 0);
          //将背景转化为图像格式,用以显示
          cvConvert(pBkMat, pBkImg);

          //显示图像
          cvShowImage("video", pFrame);
          cvShowImage("background", pBkImg);
          cvShowImage("foreground", pFrImg);

          //如果有按键事件,则跳出循环
          //此等待也为cvShowImage函数提供时间完成显示
          //等待时间可以根据CPU速度调整
          if( cvWaitKey(2) >= 0 )
            break;
        }
    }

  //销毁窗口
  cvDestroyWindow("video");
  cvDestroyWindow("background");
  cvDestroyWindow("foreground");

  //释放图像和矩阵
  cvReleaseImage(&pFrImg);
  cvReleaseImage(&pBkImg);
  cvReleaseMat(&pFrameMat);
  cvReleaseMat(&pFrMat);
  cvReleaseMat(&pBkMat);
  cvReleaseCapture(&pCapture);
  return 0;
}


七、Hougn线段检测

/* This is a standalone program. Pass an image name as a first parameter of the program.
   Switch between standard and probabilistic Hough transform by changing "#if 1" to "#if 0" and back */
#include 
#include 
#include 

int main(int argc, char** argv)
{
    const char* filename = "../hough.png";
    IplImage* src = cvLoadImage( filename, 0 );
    IplImage* dst;
    IplImage* color_dst;
    CvMemStorage* storage = cvCreateMemStorage(0);
    CvSeq* lines = 0;
    int i;

    if( !src )
        return -1;

    dst = cvCreateImage( cvGetSize(src), 8, 1 );
    color_dst = cvCreateImage( cvGetSize(src), 8, 3 );

    cvCanny( src, dst, 50, 200, 3 );
    cvCvtColor( dst, color_dst, CV_GRAY2BGR );
#if 0
    lines = cvHoughLines2( dst, storage, CV_HOUGH_STANDARD, 1, CV_PI/180, 100, 0, 0 );  // 标准型

    for( i = 0; i < MIN(lines->total,100); i++ )
    {
        float* line = (float*)cvGetSeqElem(lines,i);
        float rho = line[0];
        float theta = line[1];
        CvPoint pt1, pt2;
        double a = cos(theta), b = sin(theta);
        double x0 = a*rho, y0 = b*rho;
        pt1.x = cvRound(x0 + 1000*(-b));
        pt1.y = cvRound(y0 + 1000*(a));
        pt2.x = cvRound(x0 - 1000*(-b));
        pt2.y = cvRound(y0 - 1000*(a));
        cvLine( color_dst, pt1, pt2, CV_RGB(255,0,0), 3, CV_AA, 0 );
    }
#else
    lines = cvHoughLines2( dst, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 50, 50, 10 ); //概率性
    for( i = 0; i < lines->total; i++ )
    {
        CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
        cvLine( color_dst, line[0], line[1], CV_RGB(255,0,0), 3, CV_AA, 0 );
    }
#endif
    cvNamedWindow( "Source", 1 );
    cvShowImage( "Source", src );

    cvNamedWindow( "Hough", 1 );
    cvShowImage( "Hough", color_dst );

    cvWaitKey(0);

    return 0;
}

八、鼠标绘图

#ifdef _CH_
#pragma package 
#endif

#include "cv.h"
#include "highgui.h"
#include 
#include 

IplImage* inpaint_mask = 0;
IplImage* img0 = 0, *img = 0, *inpainted = 0;
CvPoint prev_pt = {-1,-1};

void on_mouse( int event, int x, int y, int flags, void* zhang)
{
    if( !img )
        return;

    if( event == CV_EVENT_LBUTTONUP || !(flags & CV_EVENT_FLAG_LBUTTON) )
        prev_pt = cvPoint(-1,-1);
    else if( event == CV_EVENT_LBUTTONDOWN )
        prev_pt = cvPoint(x,y);

    else if( event == CV_EVENT_MOUSEMOVE && (flags & CV_EVENT_FLAG_LBUTTON) )
    {
        CvPoint pt = cvPoint(x,y);

        if( prev_pt.x < 0 )
            prev_pt = pt;

        cvLine( inpaint_mask, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );
        cvLine( img, prev_pt, pt, cvScalarAll(255), 5, 8, 0 );
        prev_pt = pt;
        cvShowImage( "image", img );
    }
}

int main( int argc, char** argv )

{
    char* filename = argc >= 2 ? argv[1] : (char*)"../Fruits.jpg";

    if( (img0 = cvLoadImage(filename,-1)) == 0 )
        return 0;

    printf( "Hot keys: \n"
            "\tESC - quit the program\n"
            "\tr - restore the original image\n"
            "\ti or ENTER - run inpainting algorithm\n"
            "\t\t(before running it, paint something on the image)\n" );
    cvNamedWindow( "image", 1 );
    img = cvCloneImage( img0 );
    inpainted = cvCloneImage( img0 );
    inpaint_mask = cvCreateImage( cvGetSize(img), 8, 1 );
    cvZero( inpaint_mask );
    cvZero( inpainted );
    cvShowImage( "image", img );
    cvShowImage( "watershed transform", inpainted );
    cvSetMouseCallback( "image", on_mouse, 0 );

    for(;;)
    {
        int c = cvWaitKey(0);
        if( (char)c == 27 )
            break;
        if( (char)c == 'r' )
        {
            cvZero( inpaint_mask );
            cvCopy( img0, img,0 );
            cvShowImage( "image", img );
        }

        if( (char)c == 'i' || (char)c == '\n' )
        {
            cvNamedWindow( "inpainted image", 1 );
            cvInpaint( img, inpaint_mask, inpainted, 3, CV_INPAINT_TELEA );
            cvShowImage( "inpainted image", inpainted );
        }
    }
    return 1;
}


九、Yml文件读取与写入

/***********************************************************************

 * OpenCV 2.1 example

 ***********************************************************************/
#include "cv.h"
#include "highgui.h"
#include 

using namespace cv; //下面的所有cv相关类型不用加上前缀了
using namespace std;

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

{
    FileStorage fs("../test.yml", FileStorage::WRITE); //写的形式打开yml。当然也可以打开xml,主要看后缀

    fs << "i" << 5 << "r" << 3.1 << "str" << "ABCDEFGH"; //存入整型、浮点型、字符串
    Mat writeInImg = imread( "../lena.jpg" ); //载入Lena妞的图片载入
    imshow( "Lena_from_jpg", writeInImg ); //看一看Lena妞是否健在

    fs << "lena" << writeInImg; //将Lena妞的图片矩阵插入test.yml
    fs.release();
    FileStorage readfs("test.yml", FileStorage::READ); //读的形式打开yml。当然也可以打开xml,主要看后缀

    if(readfs.isOpened() )
    {
        int i1 = (int)readfs["i"];
        double r1 = (double)readfs["r"];
        string str1 = (string)readfs["str"];
        Mat readOutImg;

        readfs["lena"] >> readOutImg; //把Lena从yml中取出
        imshow( "Lena_from_yml", readOutImg ); //看看是不是跟之前放进去的是同一个人
        std::cout<<"read out i:"<


 
  

 
  

 
  

你可能感兴趣的:(OpenCV,opencv,qt,例子,编程)