openCV图像的读写操作

文章目录

  • 一、数组下标
  • 二、指针

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++的方式逐个访问每个通道的像素值,并将像素值取反后写回图像

推荐一个零声学院免费教程,个人觉得老师讲得不错,
分享给大家:
C++初级课程链接:
https://ke.qq.com/course/444655?flowToken=1043280
Qt课程链接:
https://ke.qq.com/course/444655?flowToken=1044614

你可能感兴趣的:(OpenCV学习,opencv,计算机视觉,图像处理)