大家好,又见面了,我是你们的朋友全栈君。
灰度图像遍历的三种方法
实现代码:
#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://javaforall.cn/139836.html原文链接:https://javaforall.cn
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有