1. 程式人生 > >linux openCV 顯示圖片例程

linux openCV 顯示圖片例程

1.編寫程式碼 opencv_test.cpp

#include <stdio.h>
#include <cv.h>
#include <highgui.h>

//使用cv這個名稱空間
using namespace cv;

/*    主函式
 *C語言規定main函式只能有兩個引數,
 *習慣上將這兩個引數寫成argc和argv。
 *第一個代表(傳參個數+1),
 *第二個代表傳慘資料。
 *一般有兩種寫法:
 *main( int argc, char* argv[])
 *main( int argc, char** argv)
 */
int main( int argc, char** argv )
{
  //建立一個Mat型別的變數image
  Mat image;
  /* API中有:
   * C++: Mat imread(const string& filename, int flags=1 )
   * 意思是返回Mat型別資料,第一個引數接受一個string型別的引用,
   * 第二個引數接受一個int型別的flags,一般都是1。
   */
  image = imread( argv[1], 1 );

  //當傳的引數不是一個,或者圖片沒有資料則提示沒有圖片並退出程式
  if( argc != 2 || !image.data )
    {
      printf( "沒有該圖片 \n" );
      return -1;
    }
  
  //C++: void namedWindow(const string& winname, int flags=CV_WINDOW_AUTOSIZE )
  namedWindow( "顯示圖片", CV_WINDOW_AUTOSIZE );
  //C++: void imshow(const string& winname, InputArray mat)
  imshow( "顯示圖片", image );
  //C++: int waitKey(int delay=0)
  waitKey(0);

  return 0;
}
2.編譯(使用此法則不需3、4步)

~/code$ g++ `pkg-config --cflags opencv` -o opencv_test opencv_test.cpp `pkg-config --libs opencv`

3.Makefile

在同一目錄新建Makefile檔案

CC=g++
#CFLAGS+=-g
CFLAGS+=`pkg-config --cflags opencv`
LDFLAGS+=`pkg-config --libs opencv`

PROG=main
OBJS=$(PROG).o

.PHONY: all clean
$(PROG): $(OBJS)
	$(CC) -o $(PROG) $(OBJS) $(LDFLAGS)

%.o: %.cpp
	$(CC) -c $(CFLAGS) $<

all: $(PROG)

clean:
	rm -f $(OBJS) $(PROG)


4.使用Makefile編譯

make

5.執行

~/code$ ./opencv_test cat.png