0

请看下面的代码

#include <iostream>
#include <opencv2\highgui\highgui.hpp>
#include <opencv2\core\core.hpp>

using namespace std;
using namespace cv;

Mat PeperAndSalt(Mat *,int);

int main()

{
    Mat image,image2;

    try
    {
        image = imread("C:/Users/Public/Pictures/Sample Pictures/Chrysanthemum.jpg");

        if(!image.data)
        {
            throw 1;
        }
    }
    catch(int a)
    {
        cout << "Error. Image does not exist" << endl;
        exit(0);
    }

    //Display Normal Image
    namedWindow("Normal Image");
    imshow("Normal Image",image);

    //Edited Image
    image2 = PeperAndSalt(&image,3000);

    namedWindow("Edited Image");
    imshow("Edited Image",image2);

    waitKey(0);
    return 0;
}

Mat PeperAndSalt(Mat *imagePtr, int numberOfPixels)
{
    srand(numberOfPixels);

    Mat newMat;

    imagePtr->copyTo(newMat);

    for(int a=0;a<numberOfPixels;a++)
    {
        int column = rand()%newMat.cols;
        int row = rand()%newMat.rows;

        if(newMat.channels()==1)
        {
            //Grey Image
            newMat.at<uchar>(column,row)= 255;
        }
        else if(newMat.channels()==3)
        {
            //Colour Image
            newMat.at<Vec3b>(column,row)[0]=255;
            newMat.at<Vec3b>(column,row)[1]=255;
            newMat.at<Vec3b>(column,row)[2]=255;
        }
    }

    return newMat;
}

此代码生成以下错误

Unhandled exception at 0x756a9617 in OpenCV1.exe: Microsoft C++ exception: cv::Exception at memory location 0x003bf2a0..

为什么是这样?请帮忙!

编辑

这是发生在 Mat.hpp 中的错误,它是 OpenCV 的内置类。我在调试时得到了这个

在此处输入图像描述

编辑

错误在这一行

image2 = PeperAndSalt(&image,3000);
4

2 回答 2

3

替换newMat.at<...>(column,row)newMat.at<...>(row,column)

这是代码的一部分。

    if(newMat.channels()==1)
    {
        //Grey Image
        newMat.at<uchar>(row,column)= 255;
    }
    else if(newMat.channels()==3)
    {
        //Colour Image
        newMat.at<Vec3b>(row,column)[0] = 255;
        newMat.at<Vec3b>(row,column)[1] = 255;
        newMat.at<Vec3b>(row,column)[2] = 255;
    }
于 2013-04-09T16:05:01.340 回答
2

根据 GDB 的输出:

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x00000001029fe2ed
0x0000000100001f60 in PeperAndSalt (imagePtr=0x7fff5fbff820, numberOfPixels=3000) at chrys.cpp:65
65              newMat.at<Vec3b>(column,row)[0]=255;

崩溃发生在:

newMat.at<Vec3b>(column,row)[0]=255;

这意味着您正在尝试访问Mat不存在的位置。要么不在有效范围内columnrow

狩猎愉快!

于 2013-04-09T15:25:12.993 回答