opencv学习笔记(4):图像操作

读写像素
opencv学习笔记(4):图像操作_第1张图片

int gray = gray_src.at<uchar>(row, col);

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

修改像素值
opencv学习笔记(4):图像操作_第2张图片
Vec3b和Vec3f
opencv学习笔记(4):图像操作_第3张图片
将输入图片转为灰度图并取反

#include
#include

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
	Mat src,gray_src;
	src = imread("F:/1.jpg");
	if (src.empty())
	{
		cout << "load image unsuccessfully" << endl;
		return -1;
	}
	namedWindow("source", WINDOW_AUTOSIZE);
	imshow("source", src);
	cvtColor(src, gray_src, CV_BGR2GRAY);
	namedWindow("output", WINDOW_AUTOSIZE);
	
	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("output", gray_src);
	waitKey(0);
	return 0;
}

取反(单通道和三通道)

#include
#include

using namespace std;
using namespace cv;

int main(int argc, char** argv)
{
	Mat src,gray_src;
	src = imread("F:/1.jpg");
	if (src.empty())
	{
		cout << "load image unsuccessfully" << endl;
		return -1;
	}
	namedWindow("source", WINDOW_AUTOSIZE);
	imshow("source", src);
	cvtColor(src, gray_src, CV_BGR2GRAY);
	Mat dst;
	dst = src.clone();
	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=dst.at<Vec3b>(row, col)[0];
				int g = dst.at<Vec3b>(row, col)[1];
				int r = dst.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;
			}
		}
	}
	namedWindow("dst", WINDOW_AUTOSIZE);
	imshow("dst", dst);
	waitKey(0);
	return 0;

bitwise_not(src, dst);也可实现反色

你可能感兴趣的:(opencv,opencv)