OPENCV入門教程四:imread函式讀入影象?

學習imread()函式正確讀入影象的方式,imread()用不對,對以後的影象處理有很大的影響。 有時候圖片是灰度圖,但是你用imread()讀入後它就變成了彩色圖,只不過它的三個通道的值是一樣的。 灰度圖是單通道的。 彩色圖是三通道的(B,G,R),但是彩色影象的三通道的值相同時它也是灰色的。

工具/原料

visual studio 2015

opencv2.4.13

方法/步驟

函式原型:

Mat imread( const String& filename, int flags = IMREAD_COLOR );

第一個引數是圖片的絕對地址 第二個引數表示圖片讀入的方式(flags可以預設,預設時flags=1,表示以彩色圖片方式讀入圖片) flags>0時表示以彩色方式讀入圖片 flags=0時表示以灰度圖方式讀入圖片 flags<0時表示以圖片的本來的格式讀入圖片

OPENCV入門教程四:imread函式讀入影象

開啟VS2015選擇檔案,然後新建專案,選擇新建一個Win32控制檯應用程式,並選擇空專案,並在原始檔中新增一個名為opencv的CPP檔案,並新增一下程式碼

#include "cv.h" // OpenCV 檔案頭

#include "highgui.h"

#include "cvaux.h"

#include "cxcore.h"

#include "opencv2/opencv.hpp"

#include "opencv2/imgproc.hpp"

#include

#include

using namespace cv;

using namespace std;

int main()

{

Mat image1, image2, image3, image4, image5, image6;//Mat是OpenCV最基本的資料結構,這是定義一個影象矩陣型別

image1 = imread("C:\\Users\\lidabao\\Desktop\\Lena.bmp");//讀入圖片資料

cout << "原圖1的通道數:" << image1.channels() << endl;

namedWindow("原圖1", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖1", image1); // 在視窗中顯示圖片

image2 = imread("C:\\Users\\lidabao\\Desktop\\Lena1.bmp");//讀入圖片資料

cout << "原圖2的通道數:" << image2.channels() << endl;

namedWindow("原圖2", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖2", image2); // 在視窗中顯示圖片

image3 = imread("C:\\Users\\lidabao\\Desktop\\Lena.bmp", 0);//讀入圖片資料

cout << "原圖3的通道數:" << image3.channels() << endl;

namedWindow("原圖3", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖3", image3); // 在視窗中顯示圖片

image4 = imread("C:\\Users\\lidabao\\Desktop\\Lena1.bmp", 0);//讀入圖片資料

cout << "原圖4的通道數:" << image4.channels() << endl;

namedWindow("原圖4", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖4", image4); // 在視窗中顯示圖片

image5 = imread("C:\\Users\\lidabao\\Desktop\\Lena.bmp", -1);//讀入圖片資料

cout << "原圖5的通道數:" << image5.channels() << endl;

namedWindow("原圖5", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖5", image5); // 在視窗中顯示圖片

image6 = imread("C:\\Users\\lidabao\\Desktop\\Lena1.bmp", -1);//讀入圖片資料

cout << "原圖6的通道數:" << image6.channels() << endl;

namedWindow("原圖6", WINDOW_AUTOSIZE); // 建立一個視窗

imshow("原圖6", image6); // 在視窗中顯示圖片

waitKey(0); // 等待一次按鍵,程式結束

return 0;

}

OPENCV入門教程四:imread函式讀入影象

C:\Users\lidabao\Desktop\Lena.bmp這是一張彩色圖片 C:\Users\lidabao\Desktop\Lena1.bmp這是一張灰度圖片

OPENCV入門教程四:imread函式讀入影象

1、在屬性頁中選擇VC++目錄

在包含目錄中新增 D:\opencv\build\include D:\opencv\build\include\opencv D:\opencv\build\include\opencv2 這三個資料夾 在庫目錄中新增 D:\opencv\build\x64\vc12\lib D:\opencv\build\x64\vc12\staticlib 這兩個資料夾

2、在屬性頁中選擇連結器,在連結器中點選輸入,在附加依賴項中新增 opencv_ts300d.lib opencv_world300d.lib 這兩個東西

OPENCV入門教程四:imread函式讀入影象

程式執行結果

OPENCV入門教程四:imread函式讀入影象

注意事項

注意opencv的配置

圖片, 函式, 通道, 影象, 灰度,
相關問題答案