【C++ Opencv】读写灰度图像,RGB图像的某个像素、修改像素值、图像取反(源码+API)
读写灰度图像,RGB图像的某个像素、修改像素值、图像取反(源码+API)
·
1. 读写像素
(1)读一个灰度图像的某点像素值
Scalar intensity=img.at<uchar>(y,x);
或者Scalar intensity =img.at<uchar>(Point(x,y))
(2)读一个RGB像素点的像素值
int b = dst.at<Vec3b>(row, col)[0]; //读取像素
int g = dst.at<Vec3b>(row, col)[1];
int r = dst.at<Vec3b>(row, col)[2];
2. 修改像素值
(1)灰度图像
img.at<uchar>(y,x)=128;
(2)RGB三通道图像
dst.at<Vec3b>(row, col)[0] = newb;
dst.at<Vec3b>(row, col)[1] = newg;
dst.at<Vec3b>(row, col)[2] = newr;
(3)空白图像赋值
img=Scalar(0);
3. 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,gray_src;
src = imread("D:/image/test.jpg");
if (src.empty()) {
cout << "could not load image...." << endl;
return -1;
}
namedWindow("input", WINDOW_AUTOSIZE);
imshow("input", src);
cvtColor(src, gray_src, COLOR_BGR2GRAY); //转成灰度图像
namedWindow("output", WINDOW_AUTOSIZE);
imshow("output", gray_src);
int height_gray = gray_src.rows;
int width_gray = gray_src.cols;
//单通道给图像做反向操作
for (int row = 0; row < height_gray; row++) {
for (int col = 0; col < width_gray; col++) {
int gray = gray_src.at<uchar>(row, col);
gray_src.at<uchar>(row, col) = 255 - gray;
}
}
namedWindow("反向", WINDOW_AUTOSIZE);
imshow("反向", gray_src);
//三通道给图像做反向操作
Mat dst;
dst.create(src.size(), src.type());
int height_color = src.rows;
int width_color = src.cols;
int channels = src.channels();
for (int row = 0; row < height_color; row++) {
for (int col = 0; col < width_color; 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];
int newb = 255 - b;
int newg = 255 - g;
int newr = 255 - r;
dst.at<Vec3b>(row, col)[0] = newb;
dst.at<Vec3b>(row, col)[1] = newg;
dst.at<Vec3b>(row, col)[2] = newr;
}
}
//三通道反向操作的API
bitwise_not(src, dst);
namedWindow("output", WINDOW_AUTOSIZE);
imshow("output", dst);
waitKey(0);
return 0;
}
更多推荐

所有评论(0)