在使用openCV时出现分段错误

时间:2017-05-23 13:35:36

标签: c++ opencv

我在尝试运行此代码时不断出现分段错误。我尝试通过更改数据类型来运行它。数据类型是否存在问题,使得uchar和float字节数不匹配。如果是这样做什么?

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, const char** argv )
{
     Mat img = imread("/home/sahiti/Downloads/images3.png", CV_LOAD_IMAGE_UNCHANGED); //read the image data in the file "MyPic.JPG" and store it in 'img'

     if (img.empty()) //check whether the image is loaded or not
     {
          cout << "Error : Image cannot be loaded..!!" << endl;
          //system("pause"); //wait for a key press
          return -1;
     }

    Mat image;
    img.convertTo(image,CV_32F);
    int w,h;
    for(w=0;w<img.size().width;w++)
    {

        for(h=0;h<img.size().height;h++)
        {

            Vec3f intensity = img.at<Vec3f>(w, h);
            float blue = intensity.val[0];
            float green = intensity.val[1];
            float red = intensity.val[2];
            float lumin=(0.2126 * red + 0.7152 *green + 0.0722 *blue);
            image.at<float>(w,h)=lumin;
        }
    }
Mat im;
image.convertTo(im,CV_8UC1);
imwrite( "/home/sahiti/gray_Image.png", im );



     return 0;
}

1 个答案:

答案 0 :(得分:0)

这一行

Vec3f intensity = img.at<Vec3f>(w, h);

应该是

Vec3f intensity = image.at<Vec3f>(w, h);

这也没有意义:

        image.at<float>(w,h)=lumin;

这是尝试将单个结果写入三通道图像。 这可能更有意义:

#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

int main( int argc, const char** argv )
{
    Mat img = imread("/home/sahiti/Downloads/images3.png",  CV_LOAD_IMAGE_UNCHANGED); //read the image data in the file "MyPic.JPG" and store it in 'img'

     if (img.empty()) //check whether the image is loaded or not
     {
          cout << "Error : Image cannot be loaded..!!" << endl;
          //system("pause"); //wait for a key press
          return -1;
     }

    Mat image;
    Mat im(img.size(), CV_8UC1);
    img.convertTo(image,CV_32F);

    int w,h;
    for(w=0;w<img.size().width;w++)
    {

        for(h=0;h<img.size().height;h++)
        {

            //Vec3f intensity = img.at<Vec3f>(w, h);
            Vec3f intensity = image.at<Vec3f>(w, h);
            float blue = intensity.val[0];
            float green = intensity.val[1];
            float red = intensity.val[2];
            float lumin=(0.2126 * red + 0.7152 *green + 0.0722 *blue);
            //image.at<float>(w,h)=lumin;
            im.at<uint8>(w,h)=lumin;
        }
    }
    //Mat im;
    //image.convertTo(im,CV_8UC1);
    imwrite( "/home/sahiti/gray_Image.png", im );



     return 0;
 }