How am I supposed to use cvReshape?
I am trying to use cvReshape to have 2 versions of the same matrix data. For instance here, gray_img is a 100x100 matrix and gray_line is a 10000x1 matrix, pointing to the same data but with a different header. This is what I am doing in OpenCV following the documentation:
CvMat * gray_img;
CvMat gray_line_header;
CvMat * gray_line;
gray_img = cvCreateImage(100, 100, IPL_DEPTH_32F, 1);
gray_line = cvReshape(gray_img, &gray_line_header, 0, 10000);
This works as intented but I feel that this is difficult to read and not elegant at all. If I understand correctly, gray_line will point to gray_line_header so I feel like I have an extra variable here.开发者_如何学C Is it possible to do what I want without declaring a matrix header or with only 2 (instead of 3) matrices declarations?
thanks
Are you committed to OpenCV's old C interface? With the C++ interface, you could do this:
cv::Mat grayImg(100, 100, CV_32FC1);
cv::Mat grayLine(grayImg);
grayLine.reshape(1,10000); //1 column, 10000 rows
Now you have two instances that point to the same data.
Your guess is right.
gray_line exactly points to the extra variable gray_line_header.
However, there seems no simple solutions to your problem......
If you code like this:
CvMat *gray_img, *gray_line;
gray_img = cvCreateMat(20, 20, CV_8U);
gray_line = cvReshape(gray_img, gray_line, 0, 40);
cvShowImage("after reshape", gray_line);
cvWaitKey(0);
It certainly gives you a segmentation fault...
To get rid of additional variable, I can only come up with 2 still not elegant solutions
use only one pointer, one actual
CvMat *gray_img, gray_line_data; gray_img = cvCreateImage(100, 100, IPL_DEPTH_32F, 1); cvReshape(gray_img, &gray_line_data, 0, 10000); CvMat *gray_line = &gray_line_data;
use only two pointer, and call cvCreateMatHeader before cvReshape
CvMat *gray_img, *gray_line; gray_img = cvCreateMat(20, 20, CV_8U); // initialize gray_img (omitted) gray_line = cvCreateMatHeader(40, 1, gray_img->type); gray_line = cvReshape(gray_img, gray_line, 0, 40); // maybe just data pointer reassigning?
精彩评论