opencvC++学习4像素操作

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

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

读一个RGB像素点的像素值
Vec3f intensity = img.at<Vec3f>(y, x); 
float blue = intensity.val[0]; 
float green = intensity.val[1]; 
float red = intensity.val[2];写像素

修改像素值

灰度图像
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 smallImg = img(r);

Vec3b与Vec3F

Vec3b对应三通道的顺序是blue、green、red的uchar类型数据。
Vec3f对应三通道的float类型数据
把CV_8UC1转换到CV32F1实现如下:
src.convertTo(dst, CV_32F);

实现像素取反的效果

代码:

#include <opencv2\opencv.hpp>

using namespace cv;
using namespace std;

int main()
{
	Mat src;
	src = imread("D:/opencvSRC/test.jpg");
	if (src.empty()) {

		printf("load image error!\n");
	}
	namedWindow("src", CV_WINDOW_AUTOSIZE);
	imshow("src", src);

	//单通道
	Mat dst1;
	cvtColor(src, dst1, CV_BGR2GRAY);
	int height = src.rows;
	int width = src.cols;
	int channels = src.channels();

	for (int row = 0; row < height; row++) {
		for (int col = 0; col < width; col++) {
			if (channels == 1) {

				int gray = dst1.at<uchar>(row, col);
				dst1.at<uchar>(row, col) = 255 - gray;
			}
		}
	}
	namedWindow("output1", CV_WINDOW_AUTOSIZE);
	imshow("output1", dst1);

	//三通道
	Mat dst;
	dst.create(src.size(), src.type());
	printf("height=%d width=%d channels=%d", height, width, channels);
	for (int row = 0; row < height; row++) {
		for (int col = 0; col < width; col++) {
			if (channels == 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;
			}
		}
	}
	namedWindow("output", CV_WINDOW_AUTOSIZE);
	imshow("output", dst);

	//一个函数解决
	Mat dst2;
	dst2.create(src.size(), src.type());

	bitwise_not(src, dst2);
	namedWindow("output2", CV_WINDOW_AUTOSIZE);
	imshow("output2", dst2);

	waitKey(0);
	return 0;
}

效果图:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值