1. 程式人生 > >opencv學習筆記之對灰度影象遍歷的三種方法

opencv學習筆記之對灰度影象遍歷的三種方法

灰度影象遍歷的三種方法

  • 通過指標訪問 
  • 通過迭代器訪問 
  • 動態地址計算,通過at()函式實現、
實現程式碼:
#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;
}

效果圖:

                

       原圖                              處理後圖像