【OpenCV系列】【四】操作像素的三种方式

在opencv中,操作像素的方法有三种,每种的速度不同,可以实际使用时测试(测试方法见【OpenCV系列】【三】计算程序运行时间),各有各的好处。

具体代码如下:

#include<opencv2/core/core.hpp>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
#include<opencv2/opencv.hpp>
#include<iostream>
using namespace std;
using namespace cv;

//指针操作
void Image1(Mat &input, Mat &output) {
	output = input.clone();
	int row = output.rows;
	int col = output.cols * output.channels();
	for (int i = 0; i < row; i++) {
		uchar * col_data = output.ptr<uchar>(i);
		for (int j = 0; j < col; j++) {
			col_data[j] = col_data[j] % 10 * 10;
		}
	}
}

//迭代器操作
void Image2(Mat &input, Mat &output) {
	output = input.clone();
	Mat_<Vec3b>::iterator begin = output.begin<Vec3b>();
	Mat_<Vec3b>::iterator end = output.end<Vec3b>();
	for (auto iter = begin; iter != end; iter++) {
		(*iter)[0] = (*iter)[0] + 2; // B
		(*iter)[1] = (*iter)[1] + 4; // G
		(*iter)[2] = (*iter)[2] + 8; // R
	}
}

void Image3(Mat &input, Mat &output) {
	output = input.clone();
	int row = output.rows;
	int col = output.cols;

	for(int i=0;i<row;i++)
		for (int j = 0; j < col; j++) {
			output.at<Vec3b>(i, j)[0] = output.at<Vec3b>(i, j)[0] + 4;
			output.at<Vec3b>(i, j)[1] = output.at<Vec3b>(i, j)[1] + 8;
			output.at<Vec3b>(i, j)[2] = output.at<Vec3b>(i, j)[2] + 12;
		}
}

int main() {
	Mat image = imread("E:/image_0004.jpg");
	imshow("s", image);
	waitKey(0);

	Mat image2;
	Image1(image, image2);
	imshow("s1", image2);
	waitKey(0);

	Mat image3;
	Image2(image, image3);
	imshow("s2", image3);
	waitKey(0);

	Mat image4;
	Image3(image, image4);
	imshow("s3", image4);
	waitKey(0);
}

可以看出,后面两种方式,需要知道图像的channels,否则会操作失败。另外,opencv读取数据后,图像数据格式格式为:BGR,不是RGB,切记,切记。

转载于:https://my.oschina.net/u/3800567/blog/1795926

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值