图像像素操作

文章目录

读写像素

读一个GRAY像素点的像素值(CV_8UC1)
Scalar intensity = img.at(y, x);
OR
Scalar intensity = img.at(Point(x, y));

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

修改像素值

灰度图像
img.at(y, x) = 128;

RGB三通道图像
img.at(y,x)[0]=128; // blue
img.at(y,x)[1]=128; // green
img.at(y,x)[2]=128; // red

空白图像赋值
img = Scalar(0);

ROI选择
Rect r(10, 10, 100, 100);
Mat smallImg = img( r);

代码演示

#include <opencv2/opencv.hpp>
#include<iostream>
#include<math.h>
#include<stdlib.h>
using namespace cv;

int main(int argc, char** argv) {
	Mat src = imread("C:/Users/admin/Desktop/lenna.png");//读入图片
	if (src.empty()) { // 特判
		printf("cannot see\n");
		return -1;
	}
	Mat dst;
	dst = src.clone();
	namedWindow("opencv setup1", CV_WINDOW_AUTOSIZE);
	imshow("opencv setup1", src);
	Mat gray_src_min;
	cvtColor(src, gray_src_min, CV_BGR2GRAY);
	Mat gray_src_max;
	gray_src_max = gray_src_min.clone();
	int h = src.rows;
	int w = src.cols;
	for (int i = 0; i < h; i++) {
		for (int j = 0; j < w; j++) {
			int b = src.at<Vec3b>(i,j)[0];
			int g = src.at<Vec3b>(i, j)[1];
			int r = src.at<Vec3b>(i, j)[2];
			gray_src_min.at<uchar>(i, j) =  min(b, min(g, r));//每个像素都取最小值,就得到灰度图像(较暗)
			gray_src_max.at<uchar>(i, j) =  max(b, max(g, r));//每个像素都取最大值,就得到灰度图像(较亮)
		}
	}
	bitwise_not(src, dst);//位操作反差,所有通道像素全反差[相当于对每个像素i执行:i = 255 - i]
	namedWindow("opencv setup2", CV_WINDOW_AUTOSIZE);
	imshow("opencv setup2",gray_src_min);
	namedWindow("opencv setup3", CV_WINDOW_AUTOSIZE);
	imshow("opencv setup3", gray_src_max);
	namedWindow("opencv setup4", CV_WINDOW_AUTOSIZE);
	imshow("opencv setup4", dst);
	waitKey(0);
	system("pause");   //以便在退出程序前调用系统的暂停命令暂停命令行
	return 0;
}

图像像素操作

上一篇:CodeForces - 717E Paint it really, really dark gray


下一篇:基于Opencv的图像卡通化