I'm a beginner in C++. The code I wrote in two different ways has different results. I think it's due to pointers, but I don't know why. Inside the return_image function, the image is fine, but outside the function, when received by pointer, the image is broken. The images of return_image2 function are all good. I've attached an OK image and an NG image.
PS C:\opencv\pjt> g++ e.cpp -o e.exe -I"c:\opencv\build\install\include" -L"c:\opencv\build\install\x64\mingw\lib" -L"c:\opencv\build\install\x64\mingw\bin" -lopencv_core470 -lopencv_highgui470 -lopencv_imgproc470 -lopencv_imgcodecs470 PS C:\opencv\pjt> ./e
#include <opencv2/highgui.hpp> // Mat
#include <opencv2/opencv.hpp> // rectangle
#include <iostream>
using namespace cv;
using namespace std;
void return_image(int x, int y, Mat* result)
{
Mat img=Mat (x, y, CV_8UC3);
int k=0;
unsigned char grid_color[x*y*3];
unsigned char *grid_color_ptr=&grid_color[0];
for (int i=0;i<x;i++) for(int j=0;j<y;j++) {
grid_color[k]=j; // B
k++;
grid_color[k]=j; // G
k++;
grid_color[k]=j; // R
k++;
}
////////////////////////////
img.data=grid_color_ptr;
////////////////////////////
rectangle(img, Rect(Point(0, 0), Point(img.cols, img.rows)), Scalar(0, 0, 255), 3, 4, 0);
*result=img;
imshow("original image", *result); // Image OK
moveWindow("original image",0,0);
}
void return_image2(int x, int y, Mat* result)
{
Mat img=Mat (x, y, CV_8UC3);
int k=0;
////////////////////////////
for (int i=0;i<x;i++) for(int j=0;j<y;j++) {
img.data[k]=j; // B
k++;
img.data[k]=j; // G
k++;
img.data[k]=j; // R
k++;
}
////////////////////////////
rectangle(img, Rect(Point(0, 0), Point(img.cols, img.rows)), Scalar(0, 0, 255), 3, 4, 0);
*result=img;
imshow("original image2", *result); // Image OK
moveWindow("original image2",0,175);
}
main() {
Mat img;
return_image(150,255,&img);
imshow("returned image", img); // Image NG
moveWindow("returned image",255,0);
Mat img2;
return_image2(150,255,&img2);
imshow("returned image2", img2); // Image OK
moveWindow("returned image2",255,175);
waitKey(0);
destroyAllWindows();
}
In
return_image, yourgrid_colorarray is going out of scope at the end of the function, though you are using a pointer to it as your data buffer forimg.This will allow
imgto point at the proper data within the scope of the function. But once the function returns and the memory from the local scope is freed,imgnow holds an invalid pointer to memory that was freed.