【OpenCV】修改像素值
图像操作
读写图像
读写像素
修改像素值
imread 可以指定加载为灰度或者RGB图像
Imwrite 保存图像文件,类型由扩展名决定
读一个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>
#include<iostream>
#include<math.h>
using namespace std;
using namespace cv;
int main(int argc, char**argv)
{
Mat src;
src = imread("3.jpg");
if (src.empty())
{
printf("cannot load the image...\n");
return -1;
}
namedWindow("input", CV_WINDOW_AUTOSIZE);
imshow("input", src);
Mat gray_src;
cvtColor(src, gray_src, CV_BGR2GRAY);
namedWindow("gray_src", CV_WINDOW_AUTOSIZE);
imshow("gray_src", gray_src);
imwrite("gray_src.jpg", gray_src);
/*
int height = src.rows;
int width = 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("gray_inverse", gray_src);
*/
Mat dst;
Mat dst1;
Mat dst2;
dst.create(src.size(), src.type());
dst1.create(src.size(), src.type());
dst2.create(src.size(), src.type());
int height = src.rows;
int width = src.cols;
int channel = src.channels();
for (int row = 0; row < height; row++) {
for (int col = 0; col < width; col++) {
if (channel == 1) {
int gray = gray_src.at<uchar>(row, col);
gray_src.at<uchar>(row, col) = 255 - gray;
}
else if (channel == 3) {
int b = src.at<Vec3b>(row, col)[0];//读取b通道值
int g = src.at<Vec3b>(row, col)[1];
int r = src.at<Vec3b>(row, col)[2];
dst.at<Vec3b>(row, col)[0] = 255 - b; //修改b通道值
dst.at<Vec3b>(row, col)[1] = 255 - g;
dst.at<Vec3b>(row, col)[2] = 255 - r;
dst1.at<Vec3b>(row, col)[0] = b;
dst1.at<Vec3b>(row, col)[0] = 0;
dst1.at<Vec3b>(row, col)[0] = r;
}
}
}
imshow("color_inverse", dst);
imwrite("color_inverse.jpg", dst);
imshow("when g=0", dst1);
imwrite("when g=0.jpg", dst1);
bitwise_not(src, dst2);//反转三通道颜色的函数
imshow("bitwise_not", dst2);
imwrite("bitwise_not.jpg", dst2);
waitKey(0);
return 0;
}
实验效果图
1.原图像
2.灰度化(cvtColor)
3.代码中dst
4.bitwise_not函数获取
5.when g通道=0