opencv转为灰度图的C++程序
时间: 2023-11-07 18:04:26 浏览: 116
下面是将图像转换为灰度图的C程序,使用OpenCV库:
```c
#include <opencv2/opencv.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
if (argc != 2)
{
cout << "Usage: " << argv[0] << " <image_path>" << endl;
return -1;
}
Mat image, gray_image;
// 读取图像
image = imread(argv[1], IMREAD_COLOR);
if (image.empty())
{
cout << "Could not open or find the image" << endl;
return -1;
}
// 转换为灰度图
cvtColor(image, gray_image, COLOR_BGR2GRAY);
// 显示原图和灰度图
namedWindow("Original image", WINDOW_AUTOSIZE);
namedWindow("Gray image", WINDOW_AUTOSIZE);
imshow("Original image", image);
imshow("Gray image", gray_image);
waitKey(0);
return 0;
}
```
在命令行中运行该程序时,需要指定要转换的图像的路径作为命令行参数,例如:
```
./gray_image /path/to/image.jpg
```
阅读全文