在這個實戰(zhàn)案例中,我們將使用Ubuntu環(huán)境下的OpenCV 2來創(chuàng)建一個簡單的圖像處理程序
sudo apt-get update
sudo apt-get install build-essential cmake git pkg-config
sudo apt-get install libopencv-dev
mkdir opencv_example
cd opencv_example
main.cpp
的C++源文件,并使用以下代碼作為示例:#include<iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Usage: ./opencv_example<image_path>"<< std::endl;
return -1;
}
cv::Mat image = cv::imread(argv[1], CV_LOAD_IMAGE_COLOR);
if (!image.data) {
std::cout << "No image data."<< std::endl;
return -1;
}
cv::namedWindow("Original Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Original Image", image);
cv::Mat gray_image;
cv::cvtColor(image, gray_image, cv::COLOR_BGR2GRAY);
cv::namedWindow("Grayscale Image", cv::WINDOW_AUTOSIZE);
cv::imshow("Grayscale Image", gray_image);
cv::waitKey(0);
return 0;
}
CMakeLists.txt
的文件,用于構(gòu)建項目:cmake_minimum_required(VERSION 2.8)
project(opencv_example)
find_package(OpenCV REQUIRED)
include_directories(${OpenCV_INCLUDE_DIRS})
add_executable(opencv_example main.cpp)
target_link_libraries(opencv_example ${OpenCV_LIBS})
mkdir build
cd build
cmake ..
make
./opencv_example<image_path>
將<image_path>
替換為你要處理的圖像文件的路徑。程序?qū)@示兩個窗口,一個是原始彩色圖像,另一個是轉(zhuǎn)換為灰度的圖像。按任意鍵關(guān)閉窗口。
這個簡單的示例展示了如何使用OpenCV 2讀取、顯示和處理圖像。你可以根據(jù)需要修改代碼,嘗試其他圖像處理功能。更多關(guān)于OpenCV 2的信息和教程,請訪問官方文檔:https://docs.opencv.org/2.4/index.html