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

彩色图转为灰度图

2013-05-22 15:11 731 查看
#include<opencv.hpp>
#include<opencv2\core\core.hpp>
#include<opencv2\highgui\highgui.hpp>

using namespace cv;
using namespace std;

typedef double pixel_t;

//转换为灰度图像
void ConvertToGray(const Mat& src, Mat& dst)
{
/*
Mat dst8;
if(src.channels() == 1)
{
src.copyTo(dst8);
}
else
{
cvtColor(src, dst8, CV_BGR2GRAY);
}

//dst.create(src.size(), IPL_DEPTH_64F);
dst8.convertTo(dst, CV_64F, 1.0/255.0, 0);
*/

Size size = src.size();
if(dst.empty())
dst.create(size, CV_64F);
//cout << "type: "<< src.type() << " " << dst.type()<<endl;

uchar* srcData = src.data;//指向数据的指针src.data
pixel_t* dstData = (pixel_t*)dst.data;//指向数据的指针dst.data
int dstStep = dst.step/sizeof(dstData[0]);//  sizeof(dstData[0])=8    dst.step=8*512   dstStep=512

for(int j = 0; j < src.cols; j++)
{
for(int i = 0; i < src.rows; i++)
{

//double b = *(srcData + src.step * i + src.channels() * j + 0) / 255.0;
//double g = *(srcData + src.step * i + src.channels() * j + 1) / 255.0;
//double r = *(srcData + src.step * i + src.channels() * j + 2) / 255.0;

double b = *(srcData + src.step[0] * i +src.step[1] *j + 0) / 255.0;
double g = *(srcData + src.step[0] * i +src.step[1] *j + sizeof(uchar)) / 255.0;
double r = *(srcData + src.step[0] * i +src.step[1] *j + sizeof(uchar)+sizeof(uchar)) / 255.0;

//*((dstData + dstStep * i + dst.channels() * j)) = (b + g + r)/3.0;
*((dstData + dstStep * i +  dst.channels() *j)) = ((b + g + r)/3.0);//单通道

}

//cout<<(int)(*(img2.data + img2.step[0] * 1 + img2.step[1] * 2  + sizeof(uchar)))<<endl;

}

cout<<"num  "<<src.step[1]<<endl;

}

int main()
{
Mat image,image_gray;
image=imread("Lena.jpg");

ConvertToGray(image,image_gray);

imshow("original",image);
imshow("gray",image_gray);

cout<<"image channels   "<<image.channels()<<endl;
cout<<"image_gray channels  "<<image_gray.channels()<<endl;

Mat img2 = imread("lena.jpg");//彩色图像
cout<<(int)img2.at<Vec3b>(1,2)[1]<<endl;//(1,2)点的G分量
cout<<(int)(*(img2.data + img2.step[0] * 1 + img2.step[1] * 2  + sizeof(uchar)))<<endl;

waitKey(22222222222);

return 0;

}



OpenCV中对Mat里面depth,dims,channels,step,data,elemSize和数据地址计算

http://ggicci.blog.163.com/blog/static/210364096201261052543349/


OpenCV图像处理 图像的点运算 ( 灰度直方图 ) 

http://ggicci.blog.163.com/blog/static/21036409620127591347744/

Mat数据操作

http://blog.csdn.net/yang_xian521/article/details/7161335
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  opencv