OpenCV Mat图像到黑白错误

时间:2016-05-01 13:35:52

标签: c++ image opencv mat

我正在尝试从目录中获取图像,使其成为黑白(灰度),然后将其写入另一个文件。我已经使用OpenCV的C库完成了它,这里是代码

#include <opencv2/opencv.hpp>
using namespace std;

void faktorial(int InSize, uchar *DataIn, uchar *DataOut)
{
    for (int i = 0, j = 0; i < InSize; i += 3, j++)
    {
        DataOut[j] = (DataIn[i] + DataIn[i + 1] + DataIn[i + 2]) / 3;
    }

}

int main()
{
    char tbLEN[] = "Assassin.jpg";

    IplImage* image;
    image = cvLoadImage(tbLEN, 1);

    IplImage *image2 = cvCreateImage(cvSize(image->width, image->height), IPL_DEPTH_8U, 1);

    int height1 = image->height;
    int width1 = image->width;
    int step = image->widthStep;
    int SizeIn = step*height1;
    int nChannels = image->nChannels;
    uchar* DatIn = (uchar*)image->imageData;
    uchar* DatOut = (uchar*)image2->imageData;

    faktorial(SizeIn, DatIn, DatOut);

    cvNamedWindow("Imagecolor");
    cvShowImage("Imagecolor", image);

    cvNamedWindow("Gray");
    cvShowImage("Gray", image2);
    cvWaitKey(0);
    return 0;
}

它工作得非常好,但由于C OpenCV已经过时,我试图用C ++做同样的事情,但是输出图像与我的预期完全不同。哪里出错了?另外,在使用 Mat img2(img.rows,img.cols,CV_8UC3)创建空图像时,我做得对吗?

这是代码。

void faktorial(int InSize, uchar *DataIn, uchar *DataOut)
{
    for(int i = 0,  j = 0; i < InSize; i += 3, j++)
    {
        DataOut[j] = (DataIn[i] + DataIn[i + 1] + DataIn[i + 2]) / 3;
    }

}

int main()
{
        Mat img = imread("Assassin.jpg", CV_LOAD_IMAGE_UNCHANGED);
        if (img.empty())
     {
          cout << "Error : Image cannot be loaded..!!" << endl;
          return -1;
     }

        uchar* DataImg = img.data;

        int Width = img.cols;
        int Height = img.rows;
        int Step = img.step;
        int SizeInImg = Step * Height;
        Mat img2(img.rows,img.cols, CV_8UC3);
        uchar* DataImg2 = img2.data;
        faktorial(SizeInImg, DataImg, DataImg2);


     namedWindow("MyWindow", CV_WINDOW_AUTOSIZE);
     imshow("MyWindow", img2);
}

输入 Input

输出继电器 Output

1 个答案:

答案 0 :(得分:0)

问题出在这里

Mat img2(img.rows,img.cols, CV_8UC3);

应该是

Mat img2(img.rows,img.cols, CV_8UC1);

您应该使用CV_LOAD_IMAGE_COLOR代替CV_LOAD_IMAGE_UNCHANGED

Mat img = imread(argv[1], CV_LOAD_IMAGE_COLOR);