圖像處理(一)
加載、修改、保存圖像
使用的函數:
- 加載圖像(用cv::imread)
- 修改圖像 (cv::cvtColor)
- 保存圖像(cv::imwrite)
加載圖像(用cv::imread)
原型:
Mat imread(const string& filename, int flags=1 );
參數:
imread功能是加載圖像文件成爲一個Mat對象
其中第一個參數表示圖像文件名稱
第二個參數,表示加載的圖像是什麼類型,支持常見的三個參數值
IMREAD_UNCHANGED (<0) 表示加載原圖,不做任何改變
IMREAD_GRAYSCALE ( 0)表示把原圖作爲灰度圖像加載進來
IMREAD_COLOR (>0) 表示把原圖作爲RGB圖像加載進來
注意:OpenCV支持JPG、PNG、TIFF等常見格式圖像文件加載
顯示圖像 (cv::namedWindos 與cv::imshow)
1.cv::namedWindos
函數原型:
void namedWindow(const string& winname,int flags=WINDOW_AUTOSIZE );
參數:
namedWindos功能是創建一個OpenCV窗口,它是由OpenCV自動創建與釋放,你無需取銷燬它。
常見用法namedWindow("Window Title", WINDOW_AUTOSIZE)
WINDOW_AUTOSIZE會自動根據圖像大小,顯示窗口大小,不能人爲改變窗口大小
WINDOW_NORMAL,跟QT集成的時候會使用,允許修改窗口大小。
2.cv::imshow
函數原型:
void imshow(const string& winname, InputArray mat);
參數:
第一個參數,const string&類型的winname,填需要顯示的窗口標識名稱。
第二個參數,InputArray 類型的mat,填需要顯示的圖像。
修改圖像 (cv::cvtColor)
函數原型:
void cvCvtColor( const CvArr* src, CvArr* dst, int code );
參數:
cvtColor的功能是把圖像從一個彩色空間轉換到另外一個色彩空間,有三個參數
第一個參數表示源圖像
第二參數表示色彩空間轉換之後的圖像
第三個參數表示源和目標色彩空間
如:COLOR_BGR2HLS 、COLOR_BGR2GRAY 等
保存圖像(cv::imwrite)
函數原型:
bool imwrite( const String& filename, InputArray img,const std::vector& params = std::vector());
注:
保存圖像文件到指定目錄路徑
只有8位、16位的PNG、JPG、Tiff文件格式而且是單通道或者三通道的BGR的圖像纔可以通過這種方式保存
保存PNG格式的時候可以保存透明通道的圖片
可以指定壓縮參數
代碼案例
#include "pch.h"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat image;
image = imread("E:\\test.jpg"); // Read the file
if (image.empty()) // Check for invalid input
{
cout << "Could not open or find the image" << std::endl;
return -1;
}
/*正常圖像輸出*/
namedWindow("Display window", WINDOW_AUTOSIZE); // Create a window for display.
imshow("Display window", image); // Show our image inside it.
namedWindow("Output window", WINDOW_AUTOSIZE);
/*灰色圖像輸出*/
Mat output_image;
cvtColor(image, output_image, COLOR_BGR2GRAY);
imshow("Output window", output_image);
waitKey(0); // Wait for a keystroke in the window
std::cout << "Hello World!\n";
}
注意:
必須有waitKey(0);否則圖像會一閃而過