04 OpenCV图像操作

佐手、 提交于 2020-02-02 21:48:04

一、读写图像

  • imread 指定加载为灰度或者RGB图像
  • imwrite 保存图像文件,类型由扩展名决定

二、读取像素值

  • 读取GRAY通道图像的值
uchar intensity = src.at<uchar>(row, col);

uchar intensity = src.at<uchar>(Point(col, row));

  • 读取三通道图像的像素值
Vec3f intensity = src.at<Vec3f>(row, col);
float blue = intensity.val[0];
float green = intensity.val[1];
float red = intensity.val[2];

Vec3f intensity = src.at<Vec3f>(row, col);
float blue = intensity.val[0];
float green = intensity.val[1];
float red = intensity.val[2];

  • 示例
#include <opencv2/opencv.hpp>
#include <iostream>

using namespace std;
using namespace cv;

int main()
{
	Mat src,gray_src;
	src = imread("images/02.png");
	if (src.empty()) {
		cout << "could not load image..." << endl;
		return -1;
	}
	namedWindow("input", CV_WINDOW_AUTOSIZE);
	imshow("input", src);

	cvtColor(src, gray_src, CV_BGR2GRAY);
	namedWindow("output", CV_WINDOW_AUTOSIZE);
	imshow("output", gray_src);

	int height = gray_src.rows;
	int width = gray_src.cols;

	// 单通道
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			int gray = gray_src.at<uchar>(row, col);
			gray_src.at<uchar>(row, col) = 255 - gray;
		}
	}

	imshow("output1", gray_src);

	// 三通道
	Mat dst;
	dst.create(src.size(), src.type());
	height = src.rows;
	width = src.cols;
	int nc = src.channels();
	for (int row = 0; row < height; row++)
	{
		for (int col = 0; col < width; col++)
		{
			if (nc == 1)
			{
				int gray = gray_src.at<uchar>(row, col);
				gray_src.at<uchar>(row, col) = 255 - gray;
			}
			else if (nc == 3)
			{
				int b = src.at<Vec3b>(row, col)[0];
				int g = src.at<Vec3b>(row, col)[1];
				int r = src.at<Vec3b>(row, col)[2];
				dst.at<Vec3b>(row, col)[0] = 255 - b;
				dst.at<Vec3b>(row, col)[1] = 255 - g;
				dst.at<Vec3b>(row, col)[2] = 255 - r;

				gray_src.at<uchar>(row, col) = max(b,max(g,r));
			}
			
		}
	}
	imshow("output2", dst);


	Mat dst2;
	dst2.create(src.size(), src.type());
	bitwise_not(src, dst2);
	imshow("output3", dst2);

	imshow("output4", gray_src);

	waitKey();
	return 0;
}

三、修改像素值

  • 灰度图像
img.at<uchar>(y,x) = 128;
  • RGB三通道图像
img.at<Vec3b>(y,x)[0] = 128;  //blue
img.at<Vec3b>(y,x)[1] = 128;  //green
img.at<Vec3b>(y,x)[2] = 128;  //red
  • 空白图像赋值
img = Scalar(0);
  • ROI选择
 Rect r(10,10,100,100);
 Mat s = img(r);
    • Vec3b对应三通道的顺序是blue、green、red的uchar类型数据
    • Vec3f对应三通道的float类型数据
    • 把CV_8UC1转换到 CV_32F1方法:src.convertTo(dst, CV_32F);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!