需要說明的是在OpenCV3中已經將imread()和imwrite()函數轉移到imgcodecs模塊中,因此讀寫圖像時,需要包含imgcodecs.hpp頭文件,但是highgui.hpp頭文件中已經包含了該頭文件,因此不用再顯式包含了。
#include <iostream> #include <string> using namespace std; // OpenCV includes #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> using namespace cv; int main(int argc, const char** argv) { // Read images Mat color = imread("../images/eating.jpg"); Mat gray = imread("../images/eating.jpg", 0); // Write images imwrite("gray.jpg", gray); // Get same pixel with opencv function int myRow = color.cols - 1; int myCol = color.rows - 1; Vec3b pixel = color.at<Vec3b>(myRow, myCol); cout << "Pixel Value (B, G, R): (" << (int)pixel[0] << ", " << (int)pixel[1] << ", " << (int)pixel[2] << ")" << endl; // Show images imshow("Color Image", color); imshow("Gray Image", gray); // Wait for any key waitKey(0); return 0; }
顯示的圖片效果如下: