opencv:图像像素的读写操作(四)


一、图像像素读写-基于数据下表

using namespace std;
using namespace cv;

class QuickDemo
{
public:

	void pixel_visit_Demo(Mat& image)
	{
		int width = image.cols;
		int height = image.rows;
		int channel = image.channels();
		for (int row = 0; row < height; row++) 
		{
			for (int col = 0; col < width; col++) 
			{
				if (channel == 1) // 灰度图像
				{
					int pv = image.at<uchar>(row, col);
					image.at<uchar>(row, col) = 255 - pv;
				}
				else if(channel == 3) // 彩色图像
				{
					Vec3b bjr = image.at<Vec3b>(row, col);
					image.at<Vec3b>(row, col)[0] = 255 - bjr[0];
					image.at<Vec3b>(row, col)[1] = 255 - bjr[1];
					image.at<Vec3b>(row, col)[2] = 255 - bjr[2];
				}
			}
		}
		imshow("pixel-change-show", image);
		waitKey(0);
	}
};

int main()
{
	Mat src = imread("data/right.bmp"); // 加载任意深度
	// 判断图片是否加载成功
	if (src.empty())
	{
		cout << "load image error !" << endl;
	}
	QuickDemo qd;
	qd.pixel_visit_Demo(src);
}

一、图像像素读写-基于指针

	void pixel_visit_Demo_ptr(Mat& image)
	{
		int width = image.cols;
		int height = image.rows;
		int channel = image.channels();
		for (int row = 0; row < height; row++)
		{
			uchar* current_row = image.ptr<uchar>(row);
			for (int col = 0; col < width; col++)
			{
				if (channel == 1) // 灰度图像
				{
					int pv = *current_row;
					image.at<uchar>(row, col) = 255 - pv;
				}
				else if (channel == 3) // 彩色图像
				{
					// 每次赋值完后指针后移一位,指针的方式更快
					* current_row++ = 255 - *current_row;
					* current_row++ = 255 - *current_row;
					* current_row++ = 255 - *current_row;
				}
			}
		}
		imshow("pixel-change-show", image);
		waitKey(0);
	}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值