在Debian Jessie上进行OpenCV编程

Debian Jessie对OpenCV的运行环境和开发库都进行了较大的改动。例如,libcv-dev包已经被重命名为libopencv-dev等。此外,相关动态链接库都使用libopencv_作为前缀进行命名。在链接是使用-lcv这样的方法已经不再适用了。所以,这篇文章是为了将如何编译和运行OpenCV程序的方法记录下来。

安装OpenCV开发环境

sudo apt-get install libopencv-dev

查看安装后的库和头文件

$ find /usr/lib -name "*opencv*"
...
/usr/lib/x86_64-linux-gnu/libopencv_core.so
...

$ find /usr/include -name "*opencv*"
/usr/include/opencv
/usr/include/opencv2
/usr/include/opencv2/opencv_modules.hpp
/usr/include/opencv2/opencv.hpp

Hello OpenCV

////////////////////////////////////////////////////////////////////////
//
// hello-opencv.cpp
//
// This is a simple, introductory OpenCV program. The program reads an
// image from a file, inverts it, and displays the result.
//
////////////////////////////////////////////////////////////////////////
#include <opencv/cv.h>
#include <opencv/highgui.h>

int main(int argc, char *argv[])
{
  IplImage* img = 0;
  int height, width, step, channels;
  uchar *data;
  int i, j, k;

  if (argc < 2) {
    printf("Usage: main \n\7");
    exit(0);
  }

  // load an image
  img = cvLoadImage(argv[1]);
  if (!img) {
    printf("Could not load image file: %s\n",argv[1]);
    exit(0);
  }

  // get the image data
  height    = img->height;
  width     = img->width;
  step      = img->widthStep;
  channels  = img->nChannels;
  data      = (uchar *)img->imageData;
  printf("Processing a %dx%d image with %d channels\n",
         height, width, channels);

  // create a window
  cvNamedWindow("mainWin", CV_WINDOW_AUTOSIZE);
  cvMoveWindow("mainWin", 100, 100);

  // invert the image
  for (i = 0; i < height; i++)
    for (j = 0; j < width; j++)
      for(k = 0; k < channels; k++)
        data[i * step + j * channels + k] =
                255 - data[i * step + j* channels + k];

  // show the image
  cvShowImage("mainWin", img );

  // wait for a key
  cvWaitKey(0);

  // release the image
  cvReleaseImage(&img);
  return 0;
}

编译

$ g++ -o /tmp/hello-opencv hello-opencv.cpp -lopencv_core -lopencv_highgui

运行

$ /tmp/hello-opencv /tmp/test.jpg

这个程序会创建一个窗口并且将输入的图像转换成反色显示。

发表评论