opencv入门教程 <一>
2014-06-15 22:08
302 查看
读取照片
所用函数:Mat
imread(const string& filename, int flags) (C++ function)
其中:filename为文件名,flags代表读取方式,默认情况下读取通道为3,当设置为0时,
读入灰度图.
使用方法:Mat src = imread("fruits.jpg");
注意:假设项目opencv_1,则需要将照片放置在../opencv_1/opencv_1目录下。
写回照片
所用函数:bool imwrite(const string& filename,
InputArray img,
consvector<int>& params=vector<int> () )
其中:filename为文件名,img为将要保存的图片,第三个参数通常忽略。
使用方法: imwrite("grey.jpg",grey);
注意:在保存的时候,文件名的后缀决定了文件的格式。
访问像素
所用函数:Scalarintensity=img.at<uchar>(y,x);
(针对灰度图)
Vec3bintensity
=img.at<Vec3b>(y,x);(针对3通道图)
ucharblue=
intensity.val[0];
uchargreen=
intensity.val[1];
ucharred=
intensity.val[2];
注意:uchar为无符号字符,需要转化为整数方能正常显示。
修改像素
所用函数:img.at<uchar>(y,x)=128;
(针对灰度图)
使用方法:grey.at<uchar>(grey.cols/2,grey.rows/2) = 255 ;
注意:255代表白色,0代表黑色。
显示图片
所用函数:void imshow(const string& winname,
InputArray mat)
其中:winname为窗口的名称,mat为要现实的照片。
使用方法:imshow("test",grey);
注意:在显示图片时,不一定要显示创建窗口,系统会自行按需创建。
综合例子
#include <cv.h> #include <iostream> #include <highgui.h> using namespace cv; using namespace std; int main() { //读取默认通道(3个通道)照片 Mat src = imread("fruits.jpg"); namedWindow("src", CV_WINDOW_AUTOSIZE); //获取照片中心像素值,包括三个分量 Vec3b intensity = src.at<Vec3b>(src.cols/2, src.rows/2); uchar blue = intensity.val[0]; uchar green = intensity.val[1]; uchar red = intensity.val[2]; cout<<"The blue value is "<<(int)blue<<endl; cout<<"The green value is "<<(int)green<<endl; cout<<"The red value is "<<(int)red<<endl; imshow("src",src); //读取灰度图,参数0代表单通道(灰度) Mat grey = imread("fruits.jpg",0); namedWindow("grey",CV_WINDOW_AUTOSIZE); imshow("grey",grey); //访问中心的像素值,获得一个范围在0-255之间的整数 Scalar intensity_grey = grey.at<uchar>(grey.cols/2, grey.rows/2); cout<<"The grey value is "<<intensity_grey.val[0]<<endl; //设置中心的像素值 grey.at<uchar>(grey.cols/2,grey.rows/2) = 255 ; imshow("test",grey); imwrite("grey.jpg",grey); waitKey(0); return 0; }
实验效果图
真实图片
灰度图
将中心点像素值改为255的结果
本篇博文完整工程下载地址,工程名称为Opencv_1。
如有疑问或者建议,欢迎留言。。。
相关文章推荐
- OpenCV学习教程入门篇<一、介绍>
- OpenCV学习教程入门篇<一、介绍>
- C语言指针教程----入门到精通<一>
- Git的入门教程<一>
- Linux 入门常用命令<一>
- SQL入门笔记<一>
- 【LaTeX排版】LaTeX使用--入门基础<一>
- 机器学习入门指引<一>
- DWR 入门教程 之 <signatures>标签使用
- Delphi开发Windows服务程序教程<一>
- C语言指针教程----入门到精通<二>
- 【LaTeX排版】LaTeX使用--入门基础<一>
- PySide 简易教程<一>-------Hello PySide
- PDF文件操作API之PDFBox<一> PDFBox入门
- Cocos2d入门 <一>建立一个新工程
- MongoDB<一>基础入门
- 关于怎样使用three.js的小教程<一>
- <转>Windows下用xcode开发swift程序的图文教程 <一>
- Opencv2 computer vision application programming cookbook<一>
- 制作Kinect体感控制小车教程 <一>