c opencv对灰度图像遍历的三种方法

灰度图像遍历的三种方法

  • 通过指针访问 
  • 通过迭代器访问 
  • 动态地址计算,通过at()函数实现、

实现c代码:

#include<opencv2/opencv.hpp>
#include<iostream>
 
using namespace cv;
using namespace std;
int main()
{
	Mat Img=imread("1.jpg",0);
	if(!Img.data)  
    {  
        cout<<"could not open"<<endl;  
        return -1;  
    }  
	imshow("src",Img);
 
	Mat d_Img = Img.clone();
	const int channels=d_Img.channels();
 
	int nRows=d_Img.rows;
	int nCols=d_Img.cols*channels;
    //用指针访问像素,速度最快
	uchar *p;
	for(int i=0;i<nRows;i++)
	{
		p=d_Img.ptr<uchar>(i);//获取每行首地址
		for(int j=0;j<nCols;++j)
		{
			if(p[j]>128)
				p[j]=0;
			else
				p[j]=255;
		}
	}
 
/*	//通过迭代器访问,最安全
	{
		MatIterator_<uchar>it,end;
		for(it=d_Img.begin<uchar>(),end=d_Img.end<uchar>();it!=end;++it)
		{
			if(*it>128)
				*it=0;
			else
				*it=255;
		}
	}
*/	
/*	// 动态地址计算,通过at()函数实现
	for(int i=0;i<d_Img.rows;++i)
	{
		for(int j=0;j<d_Img.cols;++j)
		{
			if(d_Img.at<uchar>(i,j)>128)
				d_Img.at<uchar>(i,j)=0;
			else
				d_Img.at<uchar>(i,j)=255;
		}
	}
	*/
	imshow("dst",d_Img);
	waitKey(0);
	return 0;
}

参考:https://blog.csdn.net/what_lei/article/details/54645803

猜你喜欢

转载自blog.csdn.net/weixin_41770169/article/details/94463075