OpenCV学习笔记(二)

来源:互联网 发布:淘宝上苹果找回可信吗 编辑:程序博客网 时间:2024/05/17 02:47

今天学习了OpenCV中数据类型和数据结构的一些知识,由于过于琐碎,就不写上来了,另外有很多东西自己还是没弄懂,比如各种类和template之类与C++ OOP有关的东西,以后还要慢慢学。晚上实现了对图片像素的访问,先是看了learning OpenCV上的cv::at<>()的用法,然后又参考了别人的博客

http://blog.csdn.net/moc062066/article/details/6949826

其中最让我困惑的还是用at取三通道彩色像素的值时,一定要用<Vec3b>,用Vec3i Vec3s Vec3w Vec3f都不行,这里实在不是太懂,为什么一定是Mat的像素一定是uchar这种类型。后来在豆瓣上找到了这个:

depth:深度,即每一个像素的位数(bits),在opencv的Mat.depth()中得到的是一个 0 – 6 的数字,分别代表不同的位数:enum { CV_8U=0, CV_8S=1, CV_16U=2, CV_16S=3, CV_32S=4, CV_32F=5, CV_64F=6 }; 可见 0和1都代表8位, 2和3都代表16位,4和5代表32位,6代表64位。因此可以通过depth判断一个图片的像素位数。代码如下:

#include <opencv2\opencv.hpp>#include <iostream>using namespace cv;using namespace std;int main(){//读入图像,本例分别使用了两个图像const char* filename="google.gif";const char* filename2="Desert.jpg";Mat mat=imread(filename,IMREAD_COLOR);Mat mat_grey=imread(filename, IMREAD_GRAYSCALE);if (mat.empty()) return -1;//判断图像的通道数和行列数int channel=mat.channels();int r=mat.rows;int c=mat.cols;int dep=mat.depth();cout<<"channel="<<channel<<endl;cout<<"size="<<r<<"*"<<c<<endl;cout<<"depth="<<dep<<endl;//取彩色图像的任一点Vec3i ans=mat.at<Vec3b>(12,3);cout<<ans<<endl;//取灰度图像的任一点int ans2=mat_grey.at<uchar>(12,3);cout<<ans2<<endl;//遍历所有像素并打印for (int i=0;i<r;++i){for (int j=0;j<c;++j){ans2=mat_grey.at<uchar>(i,j);if (ans2<245) cout<<"1"<<" ";else cout<<"0"<<" ";}cout<<endl;}//imshow("Google", mat);cv::waitKey();return 0;}


遍历图像像素的第二种方法,即使用迭代器。代码如下:

#include <iostream>#include <opencv2\opencv.hpp>using namespace std;using namespace cv;int main(){//灰度图像的迭代器遍历Mat image=imread("google.gif", CV_LOAD_IMAGE_GRAYSCALE);MatIterator_<uchar> it=image.begin<uchar>();for (;it!=image.end<uchar>();++it)cout<<(int)(*it)<<" ";cout<<endl;//彩色图像的迭代器遍历Mat image_color=imread("google.gif", IMREAD_COLOR);MatIterator_<Vec3b> it_color=image_color.begin<Vec3b>(), end=image_color.end<Vec3b>();while (it_color!=end){Vec3i ans=(*it_color);cout<<ans[0]<<" "<<ans[1]<<" "<<ans[2]<<" "<<endl;++it_color;}cout<<endl;return 0;}




使用的两个图片分别为


0 0
原创粉丝点击