1#include <opencv2/highgui.hpp>
2#include <opencv2/core.hpp>
3#include <opencv2/imgproc.hpp>
4#include <iostream>
5
6
7void RGB2Gray(const cv::Mat& src, cv::Mat& dst)
8{
9 CV_Assert(src.type() == CV_8UC3);
10 int rows = src.rows, cols = src.cols;
11
12 dst.create(src.size(), CV_8UC1);
13
14 if (src.isContinuous() && dst.isContinuous())
15 {
16 cols = rows * cols;
17 rows = 1;
18 }
19
20 for (int row = 0; row < rows; row++)
21 {
22 const uchar* src_ptr = src.ptr<uchar>(row);
23 uchar* dst_ptr = dst.ptr<uchar>(row);
24
25 for (int col = 0; col < cols; col++)
26 {
27 dst_ptr[col] = (uchar)(src_ptr[0] * 0.114f + src_ptr[1] * 0.587f + src_ptr[2] * 0.299f);
28 src_ptr += 3;
29 }
30 }
31}
32
33int main()
34{
35 cv::Mat SrcImg = cv::imread("../data/lena.jpg");
36 cv::Mat DstImg;
37 RGB2Gray(SrcImg, DstImg);
38 imshow("gray", DstImg);
39 cv::waitKey();
40 return 0;
41}