opencv第4讲--遍历图像中的每一个像素


void QuickDemo::pixel_visit_demo(Mat& image)
{
	int w = image.cols;      //获得图像的宽
	int h = image.rows;      //获得图像的高

	int dims = image.channels();  //获得图像通道的数量

	//for (int row = 0; row < h; row++)
	//{
	//	for (int col = 0; col < w; col++)
	//	{
	//		if (dims == 1)   //灰度图像
	//		{
	//			int pv = image.at(row, col);   //获得像素数值

	//			image.at(row, col) = 255 - pv;  //重新赋值
	//		}
	//		else             //彩色图像
	//		{
	//			Vec3b bgr = image.at(row, col);
	//			image.at(row, col)[0] = 255 - bgr[0];
	//			image.at(row, col)[1] = 255 - bgr[1];
	//			image.at(row, col)[2] = 255 - bgr[2];
	//		}
	//	}
	//}

	for (int row = 0; row < h; row++)
	{
		uchar* current_row = image.ptr(row);    //获取当前行的指针
		for (int col = 0; col < w; col++)
		{
			if (dims == 1)   //灰度图像,一个通道
			{
				int pv = *current_row;   //获得像素数值

				*current_row++ = 255 - pv;  //重新赋值
			}
			else             //彩色图像, 三个通道
			{
				*current_row++ = 255 - *current_row;
				*current_row++ = 255 - *current_row;
				*current_row++ = 255 - *current_row;
			}
		}
	}



	imshow("像素读写演示", image);
}