opencv图像处理03-像素的读写操作

1. 像素的读写操作:

l读一个GRAY像素点的像素值(CV_8UC1

Scalar intensity = img.at<uchar>(y, x);

l读一个RGB像素点的像素值

Vec3f intensity = img.at<Vec3f>(y, x);

float blue = intensity.val[0];

float green = intensity.val[1];

float red = intensity.val[2];

2.简单案例

将图像的每一个像素值进行反转

将图像所有像素的某个通道置0

自己动手做灰度图

#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

int main()
{
	Mat src = imread("E:/7.png");
	if (src.empty()) {
		cout << "load failed" << endl;
	}

	Mat gray_src;
	cvtColor(src, gray_src, CV_BGR2GRAY);
	int height = gray_src.rows;
	int weight = gray_src.cols;
	for (int row = 0; row < height; row++) {
		for (int col = 0; col < weight; col++) {
			int gray = gray_src.at<uchar>(row, col);
			gray_src.at<uchar>(row, col) = 255 - gray;
		}
	}
	namedWindow("gray_src", CV_WINDOW_AUTOSIZE);
	imshow("gray_src", gray_src);


	Mat dst;
	dst.create(src.size(), src.type());
	height = dst.rows;
	weight = dst.cols;
	int nc = dst.channels();

	for (int row = 0; row < height; row++) {
		for (int col = 0; col < weight; 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;

				dst.at<Vec3b>(row, col)[0] = b;  
				dst.at<Vec3b>(row, col)[1] = g;
				dst.at<Vec3b>(row, col)[2] = 0;

				//自己动手做灰度图
				gray_src.at<uchar>(row, col) = max(r, max(b,g));
			}
		}
	}

	//namedWindow("test2", CV_WINDOW_AUTOSIZE);
	imshow("dst", dst);
	imshow("gray_src", gray_src);

	/*Mat dst2;
    //该API可以得到上面同样的效果
	bitwise_not(src, dst2);
	namedWindow("test3", CV_WINDOW_AUTOSIZE);
	imshow("test3", dst2);*/


	waitKey(0);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qinchao315/article/details/81262696