OpenCV4-入门学习(一)


 

目录

图像读取及显示

图像分离通道显示


  • 图像读取及显示

//第一个例子:显示图像
void loadImage() {
	Mat  image, grayImage;
/*		常用参数:
		IMREAD_UNCHANGED = -1,	 return the loaded image as is (with alpha channel, otherwise it gets cropped).
		IMREAD_GRAYSCALE = 0,	 always convert image to the single channel grayscale image (codec internal conversion).
		IMREAD_COLOR = 1,		 always convert image to the 3 channel BGR color image.
		IMREAD_ANYDEPTH = 2,	 return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
		IMREAD_ANYCOLOR = 4,     the image is read in any possible color format.
*/
	//读取图像
	image = imread("dog.jpg", IMREAD_UNCHANGED);
	//判断图像是否有效
	if (!image.data) {
		cout << "read image failed.\n" << endl;
		return;
	}
	
	//创建一个窗口,默认的创建窗口的namedWindow参数为WINDOW_AUTOSIZE...
	//WINDOW_AUTOSIZE:窗口大小会自动调整以适应所显示的图像,但是不能更改大小
	//WINDOW_NORMAL:用户可以改变窗口的大小
	//WINDOW_OPENGL: 窗口创建的时候会支持OpenGL
	namedWindow("SrcImage", WINDOW_AUTOSIZE);
	imshow("SrcImage", image);
	
	

	
	//彩色图转为灰度图
	cvtColor(image, grayImage, COLOR_RGB2GRAY, 0);
	namedWindow("GrayImage", WINDOW_AUTOSIZE);
	imshow("GrayImage", grayImage);

	cout << "Image Size: " << image.size << endl;
	cout << "Original Image Channels: " << image.channels() << endl;
	cout << "Gray Image Channels: " << grayImage.channels() << endl;
	waitKey(0);
}

 OpenCV4-入门学习(一)_第1张图片

  •  图像分离通道显示


//实现图像分离-合并,并用图像相减测试
void testSplit() {
	Mat mat1 = imread("RGB.jpg", IMREAD_COLOR);
	if (!mat1.data) {
		cout << "read image failed.\n" << endl;
		return;
	}
	namedWindow("orignal", 1);
	imshow("orignal", mat1);


	//图像分割  分离通道排列顺序是BGR
	Mat vec[3];
	split(mat1, vec);
	imshow("blue", vec[0]);
	imshow("green", vec[1]);
	imshow("red", vec[2]);

	//图像合成,注意:合成顺序也是BGR
	Mat mat2;
	merge(vec, 3,  mat2);
	imshow("merge", mat2);

	//图像相减
	Mat mat3;
	absdiff(mat1, mat2, mat3);
	imshow("error", mat3);
	waitKey(0);
}

实验结果:可以看出分离后再合并的结果与原图像一致,,,需要注意的是分离后图像存储顺序是BGR

OpenCV4-入门学习(一)_第2张图片

  • 设置图像感兴趣区域

      


//openCV 图像复制与设置感兴趣区域
void testImage() {

	Mat src = imread("dog.jpg", IMREAD_COLOR);
	Mat copySrc1 = src;				//只会复制头部和指向像素数据的指针
	
	Mat copySrc2 = src.clone();		//完全复制

	Mat copySrc3;
	src.copyTo(copySrc3);			//完全复制

	imshow("src",src);

	
	//imshow("copySrc",copySrc1);
	//imshow("copySrc2", copySrc2);
	imshow("copySrc3", copySrc3);
	

	//设置感兴趣区域
	Mat getROI = src( Rect(50, 50, 100, 100) );//Rect四个形参分别是:x坐标,y坐标,长,高;注意(x,y)指的是矩形的左上角点
	imshow("ROI", getROI);

	//标注图像区域
	rectangle(src, Rect(50, 50, 100, 100), Scalar(255, 0, 0), 2);//2==thickness
	imshow("AddRect", src);
	
	
	waitKey(0);
}

OpenCV4-入门学习(一)_第3张图片

你可能感兴趣的:(图像处理)