Skip to content

opencvとc++で画素ごとのアクセスをやってみる

mechamogera edited this page Oct 24, 2012 · 4 revisions

環境

  • OSX 10.7.5
  • homebrew 0.9.2
  • opencv 2.4.2
    • brew install opencvで簡単にインストールできた

ソードコード

  • SOURCE.JPGを実行してみると同じ画像のDST.JPGが出来る
  • test.cpp
    #include <cxcore.h>
    #include <highgui.h>
    
    int main(void)
    {
      cv::Mat mat = cv::imread("SOURCE.JPG", -1);
      if(!mat.data)
      {
         return-1;
      }
      cv::Mat out(mat);
    
      for(int y = 0; y < mat.rows; y++)
      {
         for(int x = 0; x < mat.cols; x++)
         {
            CvMat mat_ = mat;
            CvMat out_ = out;
            cvSet2D(&out_, y, x, cvGet2D(&mat_, y, x));
         }
      }
      cv::imwrite("DST.JPG", out);
    
      return 0;
    }
  • Makefile
    CC = g++                                                                                                                                                                                       
    LDFLAGS  += `pkg-config opencv --libs`
    CFLAGS   += `pkg-config opencv --cflags`
    CXXFLAGS += `pkg-config opencv --cflags`
    
    a.out: test.o
        $(CC) -o a.out ${LDFLAGS} test.o
         
    .cpp.o:
        $(CC) $(CXXFLAGS) -c $<

高速化について

  • ループをこんな感じにすれば関数呼び出しのオーバーヘッドがない分早いらしい(実際少し早かった)
    int channels = out.channels();
    int out_step = out.step;
    int mat_step = mat.step;
    
    for(int y = 0; y < mat.rows; y++)
    {
       for(int x = 0; x < mat.cols; x++)
       {
          for (int channel = 0; channel < channels; channel++)
          {
             out.data[y * out_step + x + channel] = mat.data[y * mat_step + x + channel];
          }
       }
    }

参照

Clone this wiki locally