您的位置:首页 > 运维架构

opencv入门教程 <一>

2014-06-15 22:08 302 查看


本篇博文作为系列博文的第一篇,主要讲解一些opencv的基本操作,包括读取、写回、访问像素、修改像素、显示照片。

读取照片
    所用函数: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 图片