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




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章