最近开始学习OpenCV,记录一下学习笔记,便于复习巩固。
本代码的功能、作用:
1.读取并显示图像;
2.对rgb图像进行灰度化、高斯模糊、降采样处理
3.读、写某处的像素值
#include
#include
using namespace cv;
int main(int argc, char **argv) {
//创建显示输入、输出图像的窗口
namedWindow("img_rgb", WINDOW_AUTOSIZE); //原图:rgb图像
namedWindow("img_gray", WINDOW_AUTOSIZE); //灰度图
namedWindow("img_gauss", WINDOW_AUTOSIZE); //gaussian模糊
namedWindow("img_pyr", WINDOW_AUTOSIZE); //img_pyr为降采样得到的图像
namedWindow("img_canny", WINDOW_AUTOSIZE); //canny边缘检测图像
//读入图像,并显示
Mat img_rgb = imread("D:\\OpenCV_Test\\车牌.jpg");
//Mat img = imread("D:/OpenCV_Test/车牌.jpg"); //或者这样写路径
if (img_rgb.empty()) {
std::cout << "读入图像失败!" << std::endl;
return -1;
}
imshow("img_rgb", img_rgb);
//创建输出图像对象:申请Mat图像结构 对象
Mat img_gray, img_gauss, img_pyr, img_canny;
//对输入图像进行处理
cvtColor(img_rgb, img_gray, cv::COLOR_BGR2GRAY); //灰度图
GaussianBlur(img_rgb, img_gauss, Size(5, 5), 3, 3); //高斯模糊
pyrDown(img_rgb, img_pyr); // 降采样
Canny(img_rgb, img_canny, 10, 200, 3, true);
//显示输出图像
imshow("img_gray", img_gray);
imshow("img_gauss", img_gauss);
imshow("img_pyr", img_pyr);
imshow("img_canny", img_canny);
//*********读写某处的像素值******************
int x = 16, y = 32;
Vec3b intensity = img_rgb.at(y, x);
uchar blue = intensity[0];
uchar green = intensity[1];
uchar red = intensity[2];
//输出原图像rgb图像在点(x,y)处的像素值
std::cout << "img_rgb : pixels At (x , y) = (" << x << "," << y << ") : (blue, green, red) = (" <<
(unsigned int)blue << ", " << (unsigned int)green << ", " << (unsigned int)red << ")" << std::endl;
//输出灰度图像在(x,y)处的灰度值
std::cout << "img_gray : Gray pixel at (x , y) is : " << (unsigned int)img_gray.at(y, x) << std::endl;
//输出采样图像在(x,y)处的像素值
std::cout << "img_pyr : Pyramid2 pixel at (x/4 , y/4) is : " << (unsigned int)img_gray.at(y/4, x/4) << std::endl;
/*Note:改变rgb图像某点处某通道的像素值,可以使用 img_rgb.at(y, x)[i] = xx; //其中i=0,1,2 */
//将img_canny图上的(x,y)处像素值设置为128
img_canny.at(x, y) = 128;
//*********************************************
//等待用户按键
waitKey(0);
destroyAllWindows();
return 0;
}