遍历图片上所有像素方法总结

来源:互联网 发布:java中如何计算时间差 编辑:程序博客网 时间:2024/05/16 11:10

方法大概有4中,这里只介绍其中3种:

一、基于c风格运算符[]访问

二、迭代法

三、核心函数LUT

这里第三种方法速度最快。如果使用指针的话,迭代法也不错。

以下为代码:

// b4.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <opencv245.h>using namespace std;using namespace cv;//c风格运算符【】访问void ScanP(Mat &img){CV_Assert(img.depth() != sizeof(uchar));int channels = img.channels();int nRows = img.rows;int nCols = img.cols * channels;if (img.isContinuous()){nCols *= nRows;nRows = 1;}for (int j = 0; j < nRows; j++){uchar* p = img.ptr<uchar>(j);for (int i = 0; i < nCols; i++){if (p[i] > 133){p[i] = 255;}}}}//运用Iterator指针来遍历void scanIterator(Mat &img){CV_Assert(img.depth() != sizeof(uchar));const int channels = img.channels();switch (channels){case 1:{MatIterator_<uchar> it, end;for ( it = img.begin<uchar>(), end = img.end<uchar>(); it != end; ++it)if (*it  > 133){*it = 255;}break;}case 3:{MatIterator_<Vec3b> it, end;for ( it = img.begin<Vec3b>(), end = img.end<Vec3b>(); it !=end; ++it){if ( (*it)[0] > 100 | (*it)[1] > 100 | (*it)[2] > 100){(*it)[0] = 255;/*(*it)[1] = 255;(*it)[2] = 255;*/}  }}}}//在进行批量图像元素查找和更改操作方法时,运用LUTvoid scanLUT(Mat &img, Mat &dst){int divideWith = 10;uchar table[256];for (int i = 0; i < 256; ++i){table[i] = i/divideWith * divideWith;}Mat lookUpTable(1, 256, CV_8U);uchar* p = lookUpTable.data;for (int i = 0; i < 256; ++i){p[i] = table[i];}LUT(img, lookUpTable, dst);}int _tmain(int argc, _TCHAR* argv[]){Mat src = imread("C:\\Users\\sony\\Desktop\\pic\\Airplane.jpg" );Mat dst;scanLUT(src, dst);imshow("img", dst);waitKey(0);return 0;}