opencv 学习随记

1.   IplImage* 类型图像上的操作  CV1

    1.1 标识字

  CvFont myfont = cvFont(1, 2);
  sprintf(buffer, "mouse click at [%d,%d]", x, y);
  cvPutText(pImage, buffer, cvPoint(winX, winY), &myfont, cvScalar(255,0,0));  //标识字

   1.2  画线 矩形  圆

                cvLine(frame,
                       cvPoint(fliph(Mark.vertex[v1][0]),flipv(Mark.vertex[v1][1])),
                       cvPoint(fliph(Mark.vertex[v2][0]),flipv(Mark.vertex[v2][1])),
                       CV_RGB(255,255,0),1,8); //画线
                cvRectangle(frame,
                            cvPoint(fliph(vx-1),flipv(vy+1)),
                            cvPoint(fliph(vx+1),flipv(vy-1)),
                            CV_RGB(0,255,255),1,8);       // 画矩形点

                cvCircle(frame,cvPoint(Mark.vertex[(2+orients_dir)%4][0],Mark.vertex[(2+orients_dir)%4][1]),
                       10,cvScalar(0,0,255)); //绘制mark位置


1.3 复制拷贝

               IplImage* frame2  ;
                frame2 = cvCloneImage(frame);

1.4  生成  灰度化处理 

    frame = cvLoadImage("./input/cmpCut41.jpg", CV_LOAD_IMAGE_UNCHANGED);
    gray = cvCreateImage(cvSize(frame->width,frame->height),IPL_DEPTH_8U,1);

    cvCvtColor(frame, gray, CV_RGB2GRAY);//灰度化
    cvThreshold(gray,gray2,threshold,255,CV_THRESH_BINARY); // 灰度二值化  阀值100


1.5  转cv::Mat

    cv::Mat mClearFrame2;

    mClearFrame2 = cv::Mat(gray).clone(); // track

1.6 显示 cvShowImage

   IplImage* frame;

cvNamedWindow( "testwindow", 1 );//zyh

cvShowImage("testwindow",frame);  //zyh 

1.7 读取摄像头 /视频   帧

   CvCapture* capture;

        // capture = cvCaptureFromCAM( camID );
        capture = cvCaptureFromFile("capture2.avi");
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640 );
        cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480 );
        //cvSetCaptureProperty( capture, CV_CAP_PROP_FPS, 60 );

        tFrame = cvQueryFrame( capture );//zyh
        if ( !capture ) {
            fprintf( stderr, "ERROR: capture is NULL \n" );
            getchar();
            return -1;
        }

1.8  图像保存

            char ImageName3[100];
            sprintf(ImageName3,"%s%d%s", "/home/agv/QrProcess/QrCodeProcess/data/output/compensate/com",ii, ".jpg");//保存的图片名
            IplImage  CompensateImage =IplImage(mClearFrame2);
            cvSaveImage(ImageName3, &CompensateImage);

2. cv::mat   图像操作  cv2

       2.1  画圆 标字  画直线

    cv::Mat GglobalMap;
    cv::circle(GglobalMap,cvPoint( miu_SLAM.at<float>(0)+mapBasePosY,miu_SLAM.at<float>(1) + mapBasePosX),
           10,CV_RGB(0,255,0),-1); //绘制mark位置
    std::string text ="robotpos";
    cv::putText(GglobalMap,text,cvPoint( miu_SLAM.at<float>(0)+mapBasePosY-20,miu_SLAM.at<float>(1) + mapBasePosX-20),
            CV_FONT_HERSHEY_COMPLEX, 1, CV_RGB(255, 0, 0) );

    //画robot方向
    float startx = miu_SLAM.at<float>(0) ;float starty = miu_SLAM.at<float>(1) ;
    float  robotR =5.0; float  robotAngle = miu_SLAM.at<float>(2) ;
    float endx = startx+ robotR*cos(robotAngle) ;float endy=starty+ robotR*sin(robotAngle) ;

    cv::line(MappingResult,
           cvPoint(startx ,starty ),
            cvPoint(endx,endy),
            CV_RGB(0,0,0),1,8);
 

      2.2  复制  copyTo   clone 

      cv::Mat globalMap;

        cv::resize(res,display,cv::Size(0,0),1.0,1.0,cv::INTER_CUBIC); // res插值像素增到 1.354倍
        //创建合成矩形
        cv::Mat composite = cv::Mat(display.rows,display.cols+globalMap.cols,CV_8UC3);

        globalMap.copyTo(compositeRoi);

           或

         compositeRoi =   globalMap.clone()


     2.3 显示

cvNamedWindow( "testwindow", 1 );//zyh
cv::imshow("testwindow", globalMap); 

    2.4 视频操作 VideoCapture

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

  2.5 截图处理

    frame = cvQueryFrame( capture );
    mClearFrame = cv::Mat(frame).clone();    
    cv::Rect cutRect( 100, 200, 20, 50); // k矩形块    
    //cvShowImage("testwindow2",frame);  //zyh
    cutout = mClearFrame(cutRect).clone(); // rk矩形块  

    cv::Mat img = cv::imread("./2.png");
    cv::Mat img_out;

    Rect rect(0, 0, 200, 50);
    img(rect).copyTo(img_out);
    cv::imshow("show",img_out);



2.6 cv::mat 保存为图片

cv::Mat globalMap;

cv::imwrite("./globalmap_result.png",globalMap);

       方法二:

 先把 cv::Mat 转为 IplImage 再用 cvSaveImage 来保存,直接用 IplImage 可以直接强制类型转 cv::Mat 为 IplImage 数据类型。

cv::Mat matrixJprg = cv::imdecode(cv::Mat(data), 1);
IplImage qImg;
qImg = IplImage(matrixJprg); // cv::Mat -> IplImage

cvSaveImage("./out.jpg", &qImg);
 


3. string->int float long

//stdlib.h 中
/* Convert a string to a floating-point number.  */
extern double atof (__const char *__nptr)
 
/* Convert a string to an integer.  */
extern int atoi (__const char *__nptr)
 
/* Convert a string to a long integer.  */
extern long int atol (__const char *__nptr)



    int ->string
std::string  QRCodeLocalizer::int2str(int num)
{
    std::stringstream ss;
    ss << num;
    std::string text = ss.str();
   return text;

}

4.文件读取 变量    FileStorage

相关连接:http://www.cnblogs.com/summerRQ/articles/2524560.html

http://blog.sina.com.cn/s/blog_6a67b5c50100mpry.html


  1. //3-16   CvFileStorage结构,数据通过CxCore数据存储函数访问  
  2. typedef struct CvFileStorage  
  3. {  
  4.     ...  //hidden fields  
  5. }CvFileStorage;

<calibFile>./data/no_distortion_big.cal</calibFile>
<cvCalibFile>./data/calibDataBoardCam.xml</cvCalibFile>

       createMap( inputData, mapFile);
       cv::FileStorage fs2(inputData[std::string("cvCalibFile")].c_str(), cv::FileStorage::READ);

        cameraMatrix = cv::Mat::eye(3, 3, CV_64F);
        distCoeffs   = cv::Mat::zeros(8, 1, CV_64F);

        //获取标定参数
        fs2["Camera_Matrix"] >> cameraMatrix;               //相机矩阵
        fs2["Distortion_Coefficients"] >> distCoeffs;        //畸变系数

cvCalibFile.xml
<?xml version="1.0"?>
<opencv_storage>
<read>"camera calibration by kint at 05.02.03"</read>
<imageCount>12</imageCount>
<cameraMatrix type_id="opencv-matrix">
  <rows>3</rows>
  <cols>3</cols>
  <dt>d</dt>
  <data>
    5.0519443370436323e+02 0. 3.2083884160474554e+02 0.
    5.0285768483869174e+02 2.3831697216475899e+02 0. 0. 1.</data></cameraMatrix>
<distCoeffs type_id="opencv-matrix">
  <rows>5</rows>
  <cols>1</cols>
  <dt>d</dt>
  <data>
    -9.2216292456289706e-02 6.5000304572855785e-02
    -6.3123997885573520e-04 3.2158869444328347e-03
    5.7265487017375147e-02</data></distCoeffs>
</opencv_storage>

void QRCodeLocalizer::createMap( MapType &inputData, char * filename)
{

    std::string line;
    std::string startBraceEnd(">");
    std::string endBraceStart("</");
    std::ifstream infile(filename);
    while (std::getline(infile, line))
    {
        bool readFine = false;
        if(line.size() > 0 && line[0] == '<' && line[line.size()-1] == '>' )
        {
            std::size_t pSBE = line.find(startBraceEnd);
            std::size_t pEBS = line.find(endBraceStart);

            if( pSBE!=std::string::npos && pEBS!=std::string::npos && pSBE < pEBS)
            {
                std::string marker1 = line.substr(1,pSBE-1);
                std::string marker2 = line.substr(pEBS+2,line.size()-pEBS-3);
                if( marker1 == marker2 )
                {
                    std::string content = line.substr(pSBE+1,pEBS-pSBE-1);
                    //cout<<"content '"<<content<<"' "<<endl;
                    inputData.insert( pair<string, string>(marker1, content) );
                    readFine = true;
                }
            }
        }

        if( readFine == true )
        {
            cout<<line<<" READ FINE "<<endl;
        }
        else
        {
            cout<<line<<" ERROR ERROR ERROR !!!!!!!!!!!!! "<<endl;
        }
    }

}

5 程序退出   exit()

函数名: exit()
所在头文件:stdlib.h
功 能: 关闭所有文件,终止正在执行的进程。
exit(1)表示异常退出.这个1是返回给操作系统的。
exit(x)(x不为0)都表示异常退出
exit(0)表示正常退出
exit()的参数会被传递给一些操作系统,包括UNIX,Linux,和MS DOS,以供其他程序使用。

stdlib.h: void exit(int status);

    frame = cvQueryFrame( capture );
    if ( frame==NULL ) {
        cout<<"ERROR: capture is NULL /AVI finish \n"<<endl;
        cv::imwrite("./globalmap_result.png",globalMap);
        exit(0);
    }



~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~相关链接~~~~~~~~~~~~~~~~~~~~~~~

http://blog.csdn.net/lu597203933/article/details/16349965       Opencv2系列学习笔记1(图像的基本操作)

小村长技术blog   http://blog.csdn.net/lu597203933

videocapture      http://docs.opencv.org/modules/highgui/doc/reading_and_writing_images_and_video.html?highlight=videocapture#videocapture 

opencv2.3读写视频   http://www.360doc.com/content/12/0418/16/8353073_204677086.shtml


你可能感兴趣的:(opencv 学习随记)