您的位置:首页 > 运维架构

opencv图像处理03-像素的读写操作

2018-07-28 16:56 489 查看

1. 像素的读写操作:

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

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

 

l读一个RGB像素点的像素值

Vec3f intensity = img.at<Vec3f>(y, x);

float blue = intensity.val[0];

float green = intensity.val[1];

float red = intensity.val[2];

 

2.简单案例

将图像的每一个像素值进行反转

将图像所有像素的某个通道置0

自己动手做灰度图

[code]#include <opencv2/opencv.hpp>
#include <iostream>
#include <math.h>

using namespace std;
using namespace cv;

int main()
{
Mat src = imread("E:/7.png");
if (src.empty()) {
cout << "load failed" << endl;
}

Mat gray_src;
cvtColor(src, gray_src, CV_BGR2GRAY);
int height = gray_src.rows;
int weight = gray_src.cols;
for (int row = 0; row < height; row++) {
for (int col = 0; col < weight; col++) {
int gray = gray_src.at<uchar>(row, col);
gray_src.at<uchar>(row, col) = 255 - gray;
}
}
namedWindow("gray_src", CV_WINDOW_AUTOSIZE);
imshow("gray_src", gray_src);

Mat dst;
dst.create(src.size(), src.type());
height = dst.rows;
weight = dst.cols;
int nc = dst.channels();

for (int row = 0; row < height; row++) {
for (int col = 0; col < weight; 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 = 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;

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

//自己动手做灰度图
gray_src.at<uchar>(row, col) = max(r, max(b,g));
}
}
}

//namedWindow("test2", CV_WINDOW_AUTOSIZE);
imshow("dst", dst);
imshow("gray_src", gray_src);

/*Mat dst2;
//该API可以得到上面同样的效果
bitwise_not(src, dst2);
namedWindow("test3", CV_WINDOW_AUTOSIZE);
imshow("test3", dst2);*/

waitKey(0);
return 0;
}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: