opencv图像操作,对单通道,三通道图像像素的读取

#include<opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
using namespace std;
using namespace cv;
int main(int argc, char**argv)
{
	Mat src,dst,gray_src;
	src = imread("D:/test1.jpg");
	if (src.empty()) {
		cout << "could not load image..." << endl;
		return -1;
	}
	cvtColor(src, gray_src, CV_BGR2GRAY);
	namedWindow("input", CV_WINDOW_AUTOSIZE);
	imshow("input",src);

	//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;
		}
	}*/

	//三通道
	dst.create(src.size(), src.type());
	
	int height =src.rows;
	int 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;
			}
		}
	}*/

	//bitwise_not(src, dst);

	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] = b;
				dst.at<Vec3b>(row, col)[1] = g;
				dst.at<Vec3b>(row, col)[2] = 0;
				gray_src.at < uchar >(row,col)= max(r, max(g, b) );
			}
		}
	}

	namedWindow("gray_invert", CV_WINDOW_AUTOSIZE);
	imshow("gray_invert", dst);

	namedWindow("output", CV_WINDOW_AUTOSIZE);
	imshow("output", gray_src);

	waitKey(0);
	return 0;

}

猜你喜欢

转载自blog.csdn.net/terry_n/article/details/80294337