Jason Blog

Opencv 讀寫圖檔基本操作

#ifndef _OPENCV_H_
#define _OPENCV_H_

#include <opencv2/opencv.hpp>
#ifdef _WIN32
#ifdef _DEBUG
//Debug   mode
#pragma comment(lib,"opencv_core231d.lib")
#pragma comment(lib,"opencv_highgui231d.lib")
#pragma comment(lib,"opencv_imgproc231d.lib")
#pragma comment(lib,"opencv_video231d.lib")
#pragma comment(lib,"opencv_ml231d.lib")
#pragma comment(lib,"opencv_legacy231d.lib")
#else
//Release   mode
#pragma comment(lib,"opencv_core231.lib")
#pragma comment(lib,"opencv_highgui231.lib")
#pragma comment(lib,"opencv_imgproc231.lib")
#pragma comment(lib,"opencv_video231.lib")
#pragma comment(lib,"opencv_ml231.lib")
#pragma comment(lib,"opencv_legacy231.lib")
#endif
#else
// other
#endif

template<class T> class Image {
private:
    IplImage* imgp;
public:
    Image(IplImage* img = 0) {
        imgp = img;
    }
    ~Image() {
        imgp = 0;
    }
    void operator=(IplImage* img) {
        imgp = img;
    }
    inline T* operator[](const int rowIndx) {
        return ((T*)(imgp->imageData + rowIndx * imgp->widthStep));
    }
};

typedef struct {
    unsigned char b, g, r;
} RgbPixel;

typedef struct {
    float b, g, r;
} RgbPixelFloat;

typedef struct {
    double b, g, r;
} RgbPixelDouble;

typedef Image<RgbPixel>       RgbImage;
typedef Image<RgbPixelFloat>  RgbImageFloat;
typedef Image<RgbPixelDouble> RgbImageDouble;
typedef Image<unsigned char>  BwImage;
typedef Image<int>            BwImageInt;
typedef Image<float>          BwImageFloat;
typedef Image<double>         BwImageDouble;
#endif
#include "opencv.h"
#include <stdio.h>

using namespace cv;
using namespace std;

int main(int argc, char* argv[]) {
    int i, j;
    const char* FileName = "lena.jpg";
    IplImage* Orig_Image = NULL;  
    IplImage* Modify_Image = NULL; 

    Orig_Image = cvLoadImage(FileName, CV_LOAD_IMAGE_COLOR);

    Modify_Image =  cvCreateImage(cvGetSize(Orig_Image), IPL_DEPTH_8U, 3);

    if (Orig_Image == NULL) {
        fprintf(stderr, "Can not load image %s\n", FileName);
        return -1;
    }

    cvShowImage("Show Orig_Image", Orig_Image);

    Modify_Image = cvCloneImage(Orig_Image);
    RgbImage BlockA(Modify_Image);

    printf("width=%d, height=%d\n", Orig_Image->width, Orig_Image->height);

    for (i = 0; i < 100; ++i) {
        for (j = 0; j < 100; ++j) {
            BlockA[i][j].r = 255;
            BlockA[i][j].g = 255;
            BlockA[i][j].b = 255;
        }
    }

    cvShowImage("Show Modify_Image", Modify_Image);
    waitKey();
    return 0;
}

opencv