【OpenCV系列】【四】操做像素的三種方式

在opencv中,操做像素的方法有三種,每種的速度不一樣,能夠實際使用時測試(測試方法見【OpenCV系列】【三】計算程序運行時間),各有各的好處。ios

具體代碼以下:測試

#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,切記,切記。ui

相關文章
相關標籤/搜索