Ask Your Question
0

Trying to do some basic operations with images, code keeps crashing and I don't know why.

asked 2016-04-13 18:48:57 -0600

D. Sanz gravatar image

Hello. I'll start by saying that I'm just now starting to learn to use OpenCV libraries and I never was an expert on C++.

I want to create a smaller Mat element out of an image and do some simple processing to it. So I created a simple function with iterations to introduce elements of the original image in a 3x3 Mat element and return it, but the code keeps crashing, even when I don't crate a function, but use it outside. I haven't been able to identify a cause. I'd appreciate help making it clear to me as to why it doesn't work. Thanks beforehand, here's my very simple piece of code:

    #include <opencv2\opencv.hpp>

using namespace cv;
using namespace std;

cv::Mat Sort3x3(cv::Mat source, int y, int x) {
    int i=0, j=0;
    cv::Mat Wind9;
    Wind9 = (3,3,CV_8UC1, (0));


    while (i<2){
        j=0;
        while (j<2){
            Wind9.at<uchar>(i,j) = source.at<uchar>(y-1+i,x-1+j);
            j=j+1;
        }
        i = i+1;
    }

    return(Wind9);
}


int main( int argc, char** argv ) {

    Mat Source = imread("saltpepper1.png", IMREAD_GRAYSCALE);
    cv::Mat Wind9;
    int i=40,j=40; //Some random test numbers for a position in the image
    Wind9 = Sort3x3(Source, i, j);






       waitKey(0);

}
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2016-04-14 02:08:31 -0600

berak gravatar image

updated 2016-04-14 02:09:31 -0600

Wind9 = (3,3,CV_8UC1, (0)); won't compile. for sure you wanted:

Wind9 = Mat(3,3,CV_8UC1, Scalar(0));

the missing Scalar is also the reason for the crash, it thinks, you're giving it a pointer.

in the long run, you should avoid using for-loops like that, it is very error-prone, and you're defeating any builtin optimization. you can easily use a ROI like this:

Mat Source = imread("saltpepper1.png", IMREAD_GRAYSCALE);
cv::Mat Wind9 = Source(Rect(39,39,3,3)); // center is 40,40
edit flag offensive delete link more

Comments

Thank you, I can't believe I had missed that part. Thanks for the part about ROIs. I think they're a much better solution.

D. Sanz gravatar imageD. Sanz ( 2016-04-14 08:35:47 -0600 )edit

Oh, another thing. If I create a ROI of a certain size, why can I access values of said Mat element that are supposedly outside of my original intended scale?

D. Sanz gravatar imageD. Sanz ( 2016-04-14 09:13:57 -0600 )edit

a ROI is a slice, refering the original image pixels, so careful there.

if you need a deep copy, use: Mat deep_copy = img(Rect(...)).clone();

berak gravatar imageberak ( 2016-04-14 09:22:19 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-04-13 18:48:57 -0600

Seen: 183 times

Last updated: Apr 14 '16