void QuickDemo::pixel_visit_demo(cv::Mat &image)
{
int w = image.cols;
int h = image.rows;
int dim = image.channels();
for (int row = 0; row < h; row++)
{
for (int col = 0; col < w; col++)
{
if (dim == 1)//灰度图像
{
int pv = image.at<uchar>(row,col);//像素是字节类型
image.at<uchar>(row, col) = 255 - pv;
}
if (dim == 3)//彩色图像
{
Vec3b bgr = image.at<Vec3b>(row, col);
image.at<Vec3b>(row, col)[0] = 255 - bgr[0];
image.at<Vec3b>(row, col)[1] = 255 - bgr[1];
image.at<Vec3b>(row, col)[2] = 255 - bgr[2];
}
}
}
for (int row = 0; row < h; row++)
{
uchar* current_row = image.ptr<uchar>(row);
for (int col = 0; col < w; col++)
{
if (dim == 1)//灰度图像
{
int pv = *current_row;
*current_row++ = 255 - *current_row;
}
if (dim == 3)//彩色图像
{
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
}
}
}
imshow("像素读写", image);
}
一、数组下标
for (int row = 0; row < h; row++)
{
for (int col = 0; col < w; col++)
{
if (dim == 1)//灰度图像
{
int pv = image.at<uchar>(row,col);//像素是字节类型
image.at<uchar>(row, col) = 255 - pv;
}
if (dim == 3)//彩色图像
{
Vec3b bgr = image.at<Vec3b>(row, col);
image.at<Vec3b>(row, col)[0] = 255 - bgr[0];
image.at<Vec3b>(row, col)[1] = 255 - bgr[1];
image.at<Vec3b>(row, col)[2] = 255 - bgr[2];
}
}
}
- 如果图像是灰度图像(通道数为1),则使用.at(row, col)来访问像素值,并将像素值取反后写回图像
- 如果图像是彩色图像(通道数为3),则使用.at(row, col)来访问像素值。将每个通道的像素值取反后写回图像
二、指针
for (int row = 0; row < h; row++)
{
uchar* current_row = image.ptr<uchar>(row);
for (int col = 0; col < w; col++)
{
if (dim == 1)//灰度图像
{
int pv = *current_row;
*current_row++ = 255 - *current_row;
}
if (dim == 3)//彩色图像
{
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
*current_row++ = 255 - *current_row;
}
}
}
- 对于灰度图像,使用指针current_row指向当前行的数据指针,然后通过*current_row++的方式逐个访问像素值,并将像素值取反后写回图像
- 对于彩色图像,同样使用指针current_row指向当前行的数据指针,然后通过*current_row++的方式逐个访问每个通道的像素值,并将像素值取反后写回图像
推荐一个零声学院项目课,个人觉得老师讲得不错,分享给大家:
零声白金学习卡(含基础架构/高性能存储/golang云原生/音视频/Linux内核)
https://xxetb.xet.tech/s/VsFMs文章来源地址https://www.toymoban.com/news/detail-630652.html
文章来源:https://www.toymoban.com/news/detail-630652.html
到了这里,关于openCV图像的读写操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!