相较于指针,有更简单的方式获取像素。指针不适合新手
下面介绍处理多通道图像的像素值:
这里发现一个很蛋疼的问题:我这个vs2017+OpenCV3.4.1的环境,当鼠标移动到Mat上的时候就会卡死,动不了了,一开始我还以为是电脑的原因。一百度发现好多人都有这个问题。找到解决方案:在Mat的源文件中,将Mat和注释之间加上一个空行,之后就没有这个问题了。——只想说,这个问题让我曾经一度十分崩溃!
1、修改图像像素值
Mat m=imread();
m.at
m.at
Vec3b,也可以写成Vec3f(浮点型)。
2、读写像素
读一个GRAY图像的像素点值(CV_8UC1):Scalar intensity=img.at
读一个RGB图像的像素值:
Vec3b intensity=img.at
或者Vec3f intensity = img.at
float blue=intensity.val[0];
float green = intensity.val[1];
float red = intensity.val[2];
另外:
将CV_8UC1转换成CV_32F1的操作:src.convertTo(dst,CV_32F);
空白图像赋值:img=Scalar(0);
3、ROI的选择:
Rect r(10,10,100,100);
Mat smallimg=img(r);
本节代码:
#include
#include
using namespace std;
using namespace cv;
int main(int argc, char** argv) {
Mat src = imread("C:\\Users\\admin\\Desktop\\demo.jpg", IMREAD_COLOR);
if (src.empty())
{
printf("Could not load image...");
return 0;
}
int n1 = src.channels();
printf("The depth of src is: %d\n", n1);
Mat dst;
cvtColor(src, dst,CV_BGR2GRAY);//第4个参数省略。。默认0
int n2 = src.channels();
printf("The depth of dst is: %d\n", n2);
namedWindow("Demo image", CV_WINDOW_AUTOSIZE);
imshow("Demo image", src);
int height = dst.rows;
int width = dst.cols;
namedWindow("output window", CV_WINDOW_AUTOSIZE);
imshow("output window", dst);
Mat m = Mat::zeros(height, width, CV_8UC1);
for (int row=0; row < height; row++)
{
for (int col = 0; col < width; col++)
{
m.at(row, col) = 255 - dst.at(row, col);
//int gray= dst.at(row, col);
//dst.at(row, col) = 255 - gray;
}
}
namedWindow("singlechannel window", CV_WINDOW_AUTOSIZE);
imshow("singlechannel window", m);
Mat m2;
m2.create(src.size(), src.type());
int height2 = src.rows;
int width2 = src.cols;
int np = src.channels();
/*
for (int row = 0; row < height2; row++)
{
for (int col = 0; col < width2; col++)
{
if (np==1)
{
dst.at(row, col) = 255 - dst.at(row, col);
}
else if(np==3){
m2.at(row, col)[0] = 255 - src.at(row, col)[0];
m2.at(row, col)[1] = 255 - src.at(row, col)[1];
m2.at(row, col)[2] = 255 - src.at(row, col)[2];
}
}
}
*/
//调用api
bitwise_not(src, m2);
namedWindow("Mulchannels window", CV_WINDOW_AUTOSIZE);
imshow("Mulchannels window", m2);
waitKey(0);
return 0;
}
效果:
//取灰度的不同方法
m3.at