OpenCV Q&A Forum - RSS feedhttp://answers.opencv.org/questions/OpenCV answersenCopyright <a href="http://www.opencv.org">OpenCV foundation</a>, 2012-2018.Mon, 14 Oct 2019 09:43:09 -0500mat.reshape giving me an offset in resulthttp://answers.opencv.org/question/219716/matreshape-giving-me-an-offset-in-result/Hi,
I have been struggling with the reshape function. I have a big matrix that I convert into a 1 column mat. When I convert the I column back to the original size, the image has an offset and doesn't fit the original no more.
Here my code more or less (PS. I have simplified it to this that demonstrates my problem):
**vb.net code:**
frame = my_Original_mat
Dim SingleColumn As Mat = frame.Clone.Reshape(0, frame.Cols * frame.Rows) 'makes it a 1 column mat
Dim Mymat As New Mat
SingleColumn.Col(0).CopyTo(Mymat) 'get the single column back out again
Dim OriginalShape As Mat = Mymat.Reshape(0, frame.Rows))
CvInvoke.Imshow("Original ", frame.Clone)
CvInvoke.Imshow("OriginalShape ", OriginalShape .Clone)
![image description](/upfiles/1571063685618789.png)
![image description](/upfiles/15710637115395028.png)
Sorry for the bad images...but I think you can see that the reshaped one is now shifted down.
What am I doing wrong? I need a way to simply extract 1 column at the time from a build up matrix (I concat into this matrix).
Let me know if anything else is needed and thanks for the help in advance.TheoDupMon, 14 Oct 2019 09:43:09 -0500http://answers.opencv.org/question/219716/how to reshape a mat like (1,3,height,width) to (height,width,3)?http://answers.opencv.org/question/212695/how-to-reshape-a-mat-like-13heightwidth-to-heightwidth3/I am using opencv4.1 under windows 7x64 with visual studio 2015
I am implementing [code](https://github.com/opencv/opencv/blob/3.4.0/samples/dnn/fast_neural_style.py) to one in C++. But it makes me confused that how to do this
out = out.reshape(3, out.shape[2], out.shape[3])
out = out.transpose(1, 2, 0)
in opencv C++ version?
lunasdejavuWed, 08 May 2019 22:23:25 -0500http://answers.opencv.org/question/212695/What does "sig[i] = cv::Mat(sigv).clone().reshape(1);" do?http://answers.opencv.org/question/193944/what-does-sigi-cvmatsigvclonereshape1-do/i KNOW `reshape()` get a vector and make a matrix from it. But why in this line of code:
sig[i] = cv::Mat(sigv).clone().reshape(1);
It came after the `clone()` ? What does this line of code do exactly?
EDIT: More information:
//Do EMD and report
//
vector<cv::Mat> sig(5);
cout << "\nEMD: " << endl;
// Oi Vey, parse histograms to earth movers signatures
//
for( i=0; i<5; ++i) {
vector<cv::Vec3f> sigv;
// (re)normalize histogram to make the bin weights sum to 1.
//
cv::normalize(hist[i], hist[i], 1, 0, cv::NORM_L1);
for( int h = 0; h < h_bins; h++ )
for( int s = 0; s < s_bins; s++ ) {
float bin_val = hist[i].at<float>(h, s);
if( bin_val != 0 )
sigv.push_back( cv::Vec3f(bin_val, (float)h, (float)s));
}
// make Nx3 32fC1 matrix, where N is the number of nonzero histogram bins
//
sig[i] = cv::Mat(sigv).clone().reshape(1);rezaeeSun, 17 Jun 2018 03:53:17 -0500http://answers.opencv.org/question/193944/why we do reshape to the matrix of an image before doing pcahttp://answers.opencv.org/question/178471/why-we-do-reshape-to-the-matrix-of-an-image-before-doing-pca/Hi. i am trying to implement PCA algorithm on an image but as i was searching i found many do reshaping to the matrix (image). i understand the concept of the PCA but when it comes to the implementation i don't know what's the benefit of reshaping the image. as far as i know reshaping matrix is like resizing the matrix.
another question.
when i reshape a matrix of 3x3 to 3x1. that means i lost information (i lost 2 columns).AhmedSh3banThu, 16 Nov 2017 09:05:39 -0600http://answers.opencv.org/question/178471/Mat reshape not reducing channel numberhttp://answers.opencv.org/question/129224/mat-reshape-not-reducing-channel-number/Hi everyone,
I get the error: <code>error: (-215) mask.depth() == CV_8U && (mcn == 1 || mcn == cn) in function copyTo</code>, when the following code runs. Why does reshape() not reduce the number of channels in mask to 1? I need a binary mask to find an object in the scene, however drawcontours() is giving me a grayscale 3 channel image, and my input image is 4 channels hence the error, but I thought reshape would fix this by reducing it to 1 channel. The printout of mcn states Mask has 3 channels.
ginisterMon, 20 Feb 2017 10:23:02 -0600http://answers.opencv.org/question/129224/How can I reshape matrix 1xn to matrix sqrt(n)xsqrt(n) ?http://answers.opencv.org/question/123305/how-can-i-reshape-matrix-1xn-to-matrix-sqrtnxsqrtn/I have matrix 1x16. I will reshape this matrix to 4x4. How can I reshape this matrix? I just use this code, but the program was break.
//transpose
Mat det0 = Mat(d1);
Mat dt1;
dt1 = det0.reshape(0,4);
cout << " Sebelum transpose "<<det0 <<endl;
cout << "coba" << dt1 <<endl;
`ShabrinaFri, 20 Jan 2017 06:49:08 -0600http://answers.opencv.org/question/123305/I want to convert 16UC3 image to 1 dimensional array?http://answers.opencv.org/question/107057/i-want-to-convert-16uc3-image-to-1-dimensional-array/ I'm unable to access the values in the matrix properly.
for (int i = 0; i < image.rows; i++)
{
for (int j = 0; j < image.cols; j++)
{
img[j + image.cols*i + image.cols*image.rows * 0] = image.at<cv::Vec3b>(i, j)[0];
img[j + image.cols*i + image.cols*image.rows * 1] = image.at<cv::Vec3b>(i, j)[1];
img[j + image.cols*i + image.cols*image.rows * 2] = image.at<cv::Vec3b>(i, j)[2];
}
}MadalasaWed, 26 Oct 2016 01:59:45 -0500http://answers.opencv.org/question/107057/mat.reshape not workinghttp://answers.opencv.org/question/90848/matreshape-not-working/Hello I have a matrix M 3x3
I use reshape(0,9) so the M.at(0,1) should be the 4th element but it becomes the 2nd element. Help please. If i am wrong then please tell me how do i convert a 2D matrix into a 1D column vector.
EDIT: I dunno how to show the code. Its too big
My matrix is 92 x 112. some of the data below.
-40 -39
-44
....
In matlab if i reshape it becomes
-40
-44
...
-39
-39 becomes the 93rd element. In opencv I reshape it becomes
-40
-39
....
-39 becomes the SECOND element and i dunno where the -44 goes to. I used M.reshape(0,92*112). Matlab is giving me the right answer
Here is the short piece of code that I have
cout << Im.at<float>(0,0) << endl;
cout << Im.at<float>(0,1) << endl;
waitKey(0);
// Reshape to column vector -- Wrong
Mat temp;
Im.reshape(0, 92*112).copyTo(temp);
cout << temp.at<float>(0,0) << endl;
cout << temp.at<float>(1,0) << endl;
What I am getting above is that the elements in (0,0) and (0,1) are equal to (0,0) and (1,0) after being reshaped. Im(0,1) should be equal to temp(113,0) or temp(93,0) but I am not getting such values. Is there another function to reshape a 2D Mat ?
**EDIT: Okay it seems like my understanding of the reshape function was totally wrong. Thanks again berak. I had thought OpenCV would go 'down' the array but it seems like OpenCV would move from top left to bottom right**NbbThu, 24 Mar 2016 02:46:02 -0500http://answers.opencv.org/question/90848/Changing Mat dimensions inplacehttp://answers.opencv.org/question/65006/changing-mat-dimensions-inplace/As part of a larger project, I have some code that does something similar to the following:
cv::Mat some_function()
{
// get some ND-array
Mat mat1 = get_some_mat();
vector<int> dims(mat1.size.p, mat1.size.p + mat1.dims);
// ... shuffle the dimensions stored in "dims" (the total() remains the same)
std::swap(dims[0], dims[1]); // only an example...
// create new mat header for the same data (no copying)
Mat mat2(dims.size(), dims.data(), mat1.type(), mat1.data);
// return matrix with the shuffled dimensions
mat1 = mat2; // <-- is this part safe??
return mat1; //
}
Is the last assignment safe, or will it mess up the ref count and leak memory?
I know the safer option is to just clone the data as in:
// return matrix with the shuffled dimensions
return mat2.clone();
but I'm trying to avoid making unnecessary copies of data...
I'm open to suggestion if there are better ways to reshape the ND-array in-place ...
You can assume the following is true:
CV_Assert(mat1.isContinuous() && mat1.dims > 3 && mat1.channels() == 1);
N.B: I am working with OpenCV 3.0.0
---
## EDIT:
Another thing I tried is to [directly overwrite](http://docs.opencv.org/modules/core/doc/basic_structures.html#mat) the Mat `size` and `step` with those from the shuffled array:
// return matrix with the shuffled dimensions
std::copy(mat2.size.p, mat2.size.p + mat2.dims, mat1.size.p);
std::copy(mat2.step.p, mat2.step.p + mat2.dims, mat1.step.p);
return mat1;
But it's not quite right.. Apparently something in the `mat1.flags` field needs to be updated as well! Any help?
---
## EDIT2:
I found an [overload](http://docs.opencv.org/master/d3/d63/classcv_1_1Mat.html#a13ccd8740a42616d650ae9495e43eb2d) of the `Mat::reshape` method for ND-arrays, unfortunately it's not yet fully implemented and currently throws a `CV_StsNotImplemented` error!
// return matrix with the shuffled dimensions
return mat1.reshape(mat2.channels(), mat2.dims, mat2.size.p);
See the [source code](https://github.com/Itseez/opencv/blob/3.0.0/modules/core/src/matrix.cpp#L4254) (either 3.0 or the master branch)...
---
## Details
Let me explain a bit more about my use case. In my actual code, I'm trying to convert the last dimension of any 1-channel ND-array into channels of a ND-array with one less dimension but multi-channels, without copying the data. (Again we can assume that the array is continuous and the destination number of channels is less than `CV_CN_MAX`).
As an example, If I had the following array:
cv::Mat get_some_mat()
{
int dims[] = {2,3,4,5}; // I'm really working with arbitrary number of dimensions
Mat matnd(4, dims, CV_64F, Scalar::all(0));
return matnd;
}
I want to convert it from 2x3x4x5 array with 1-channel into a 2x3x4 array with 5-channels, i.e:
int dims[] = {2,3,4};
Mat mat(3, dims, CV_64FC(5), Scalar::all(0));
**And I want to avoid unneeded copies**... The above `Mat::reshape` method would have been great, but it's not implemented at the moment!
The regular `Mat::reshape` leaves an undesired singleton dimension at the end:
matnd.reshape(5, 0); // returns 2x3x4x1 with 5-channel (note the "1" at the end)
Thanks and sorry for the long post :)
Amro_Sat, 27 Jun 2015 19:53:24 -0500http://answers.opencv.org/question/65006/reshape matrixhttp://answers.opencv.org/question/82904/reshape-matrix/I can achieve the following:
![image description](/upfiles/14522791797344178.jpg)
with the reshape command quite easy:
Mat a = Mat(5,1, CV_32FC3); //a is 5x1, 3 channels
Mat b = a.reshape(1); //b is 5x3, 1 channel
How about the opposite:
![image description](/upfiles/145227930419595.jpg)
I was also trying with `.reshape` but I couldn't manage it. (bear with me but my brain is quite fried at the moment)
---------------------------------------
**Update:**
I have the following image where its channel is in one big image:
![image description](/upfiles/14522813342303681.png)
so what I want to do is take each part of the image (we know the dimensions) and put it in a different channel:
![image description](/upfiles/14522814467361912.png)
in order to get the final image:
![image description](/upfiles/14522814738328045.png)
I could do it with many ways but I thought that there should be a simple way to do it like using `.reshape` or something similar. Therefore, I tried with the `.reshape` and what @LorenaGdl suggested or `.reshape(3, image.rows)` but I do not get the result I want grrrrrr, actually I am not sure if I can do that with the reshape. (by the way at the end I will be seeing nightmares with pink panthers.....:-p )theodoreFri, 08 Jan 2016 13:00:13 -0600http://answers.opencv.org/question/82904/2D matrix reshape into 3D matrixhttp://answers.opencv.org/question/59174/2d-matrix-reshape-into-3d-matrix/I Can see that opencv Reshape has been overloaded with
Mat reshape(int cn, int rows=0) const;
Mat reshape(int cn, int newndims, const int* newsz) const;
I wan to create this matlab code
original matrix gili = 2x24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
reshapeGili = 4x6x2
reshape([gili(1,:) gili(2,:)], 4, 6, 2);
val(:,:,1) =
1 5 9 13 17 21
2 6 10 14 18 22
3 7 11 15 19 23
4 8 12 16 20 24
val(:,:,2) =
25 29 33 37 41 45
26 30 34 38 42 46
27 31 35 39 43 47
28 32 36 40 44 48
Can this be done using reshape?
I can create `int newdims[] = { 4, 6, 2 };`
but what does `const int*newsz` mean?
if I can't use reshape I will just create a new matrix and copy the values to it.
int sizes[] = { 4, 6, 2 };
cv::Mat xyFinal(3, sizes, CV_64F, cv::Scalar(0));
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 6; j++)
{
xyFinal.at<double>(i,j,0) = xyFinalMat.at<double>(0,i*6+j);
xyFinal.at<double>(i,j,1) = xyFinalMat.at<double>(1,i*6+j);
}
}
the code works however when I try to print the output matrix
ofstream myfile;
myfile.open("C:\\Users\\gdarmon\\Desktop\\OpenCV_CR.txt");
myfile << xyFinal;
myfile.close();
OpenCV Error: Assertion failed (m.dims <= 2) in cv::writeMat, file C:\buildslave
64\win64_amdocl\2_4_PackSlave-win64-vc11-shared\opencv\modules\core\src\out.cpp,
line 117
Gilad DarmonMon, 06 Apr 2015 09:04:45 -0500http://answers.opencv.org/question/59174/Decorrelation askhttp://answers.opencv.org/question/24221/decorrelation-ask/Hi what I have to do is todo a decorellation on RGC components of an image to obtain an efficient decodification of input datas with PCA analysis, adapted to local statistics of image (rbgDecorr in matlab code. I finally obtain 3 components. This is done with colorDecorolletion()
You can see Matlab's code to understand better:
main (I put here my question):
[r c compc] = size(image);
numColComp = compc; % 3 in case of color images, 1 in grayscale images
inComp = reshape(im, r*c, numColComp);
Decorr=colorDecorrelation(inComp,numColComp);
rgbDecorr= reshape(Decorr, r, c, numColComp); //does it create a 3dimensional array?
clear Decorr;
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Color Decorrelation
% Input Parameters:
% im - image matrix
% numColComp - number of image channels
%
% Output value:
% Xdecorr - decorrelated image, same dimensions as the original one
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Xdecorr=colorDecorrelation(X,numColComp)
if numColComp>1
mu = mean(X);
X = bsxfun(@minus, X, mu);
A = X'*X;
[V,D,notused] = svd(A);
Xdecorr=X*V;
else % in case of a grayscale image
Xdecorr = X;
end
My C++ code:
#include <stdio.h>
#include <cxcore.h>
#include <cv.h>
#include <highgui.h>
#include <math.h>
#include <vector>
using namespace cv;
using namespace std;
#define PI 3.14159265
Mat colorDecorrelation(Mat img,int numColComp);
int main(){
if(img.empty()){
cout<<"The image is empty \n";
return -1;
}
namedWindow("Image Display", CV_WINDOW_AUTOSIZE);
imshow("Image Display", img);
waitKey(0);
destroyWindow("Image Display");
padSize = new int;
sz2filt_r = new int;
sz2filt_c = new int;
rows=img.rows;
cols= img.cols;
nChannels= img.channels();
numColComp = nChannels ;
inCompImg = img.reshape(numColComp,rows*cols);
imgDecorr = colorDecorrelation(inCompImg,numColComp);
rows=imgDecorr.rows;
cols=imgDecorr.cols;
nChannels= imgDecorr.channels();
imgDecorr.convertTo(rgbDecorrImg,CV_8UC3); //to return to first type
rgbDecorrImg = rgbDecorrImg.reshape(numColComp,img.rows); //is it a 2D image? so maybe I have an error
namedWindow("Image Display", CV_WINDOW_AUTOSIZE);
imshow("Image Display", rgbDecorrImg);
waitKey(0);
destroyWindow("Image Display");
}
residentelvioWed, 20 Nov 2013 12:10:58 -0600http://answers.opencv.org/question/24221/Reshape function problemhttp://answers.opencv.org/question/22042/reshape-function-problem/When I use the **reshape** function with **ROI** then I encounter the following error.
Mat cur_img = imread(fileList.fileNames[i],0);
Mat res_img = cur_img(Rect(0,0,100,100)).reshape(1,1);
> Error :Image step is wrong
I made a **clone** of ROI image then the error is **resolved**.
Mat cur_img = imread(fileList.fileNames[i],0);
Mat res_img = cur_img(Rect(0,0,100,100)).clone().reshape(1,1);
**What is the reason?**
**Edit:**
I realize this topic that the reshape function in this step need to consecutive memory.My question is why the reshape function don't create new image when the Mat data is not consecutive memory and then it does not reshape it .This solution is better than facing the user with an error.Mostafa SatakiMon, 07 Oct 2013 01:12:38 -0500http://answers.opencv.org/question/22042/Reshape functionhttp://answers.opencv.org/question/15419/reshape-function/Hi I have to translate from MAtlav to C this lines:
x=reshape(img,r*c,numChannels);
x=reshape(img,r,c,numChannels);
x=reshape(img,r,c);
x=reshape(img,r*c,scalesNumber);
I didn t understand well this function, but I tried with:
x=img.reshape(numColComp,rows*cols);
x=img.reshape(numColComp,rows);
x=img.reshape(numColComp,rows); //or x=img.reshape(0,rows)
x=img.reshape(0,rows);
I suppose I m doing it bad
residentelvioWed, 19 Jun 2013 11:04:08 -0500http://answers.opencv.org/question/15419/Face recognition using Eigen faces error Image step is wronghttp://answers.opencv.org/question/13706/face-recognition-using-eigen-faces-error-image-step-is-wrong/
I am doing face recognition using EigenFace Recognizer to recognize a face from training dataset i.e trained image. I have used the javacv and opencv library to developer android based face recognition using java . when i make a call to
int predictedLabel =faceRecognizer.predict(test_resizeimg); i get error
OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in cv::Mat cv::Mat::reshape(int, int) const, file /home/saudet/android/OpenCV-2.4.3/modules/core/src/matrix.cpp, line 801
can anybody advice me how to resolve this issue.
ppWed, 22 May 2013 08:57:53 -0500http://answers.opencv.org/question/13706/Reshaping matrices into column vectors??http://answers.opencv.org/question/13658/reshaping-matrices-into-column-vectors/Hi,
I have a question regarding reshaping matrices. I have two square 3x3 matrices M1 and M2. I wish to turn both matrices into 9 element column vectors c1 and c2. Next i would like to create a new matrix consisting of new 2x9 matrix [c1,c2]. I need to do this in order to solve a least square problem.
I tried using the reshape function as M1.reshape(0,9) but it returns:
OpenCV Error: Image step is wrong (The matrix is not continuous, thus its number of rows can not be changed) in reshapenapoleonTue, 21 May 2013 16:04:40 -0500http://answers.opencv.org/question/13658/Error transforming a vector via Homography matrix - C++http://answers.opencv.org/question/11873/error-transforming-a-vector-via-homography-matrix-c/I have 2 frames of a video stream done by a moving (very slow) camera; after using SIFT algorithm and findHomography OpenCv function i have the transformation matrix that describes the movement done by the camera between the 2 frames.
what i would like to do is to find a point of the first frame in the second one:
so my code is:
H = findHomography( point1, point2, CV_RANSAC ); //compute the transformation matrix using the
// matching points (the matrix is correct, i checked it)
Mat dstMat(3, 1, H.type());
vector<Point3f> vec;
Mat srcMat(3, 1, H.type());
vec.push_back(Point3f(Ptx,Pty,-1)); // fill the 3x1 vector with the coordinate
// of the interest point in frame 1
srcMat= Mat(vec).reshape(1).t(); //conversion of vec in Mat (the vector is correct, i checked it)
dstMat = H*srcMat; //compute the arrival point in frame 2 // ERROR
But, where error is written, i receive the following error:
OpenCV Error: Assertion failed (type == B.type() && (type == CV_32FC1 || type == CV_64FC1 || type == CV_32FC2 || type == CV_64FC2)) in gemm, file /tmp/buildd/ros-fuerte-opencv2-2.4.2-1precise-20130312-1306/modules/core/src/matmul.cpp, line 711
terminate called after throwing an instance of 'cv::Exception'
what(): /tmp/buildd/ros-fuerte-opencv2-2.4.2-1precise-20130312-1306/modules/core/src/matmul.cpp:711: error: (-215) type == B.type() && (type == CV_32FC1 || type == CV_64FC1 || type == CV_32FC2 || type == CV_64FC2) in function gemm
Aborted (core dumped)
Why?matteoThu, 18 Apr 2013 06:07:53 -0500http://answers.opencv.org/question/11873/opencv reshape like matlabhttp://answers.opencv.org/question/3780/opencv-reshape-like-matlab/Hi.
Let assume that there is a vector.
cv::Mat v(9,1,CV_64F);
I would like to change this to 3x3 matrix (any order is okay).
But, v.reshape() does not help anything!
I think documentation should note about reshaping (not the channel reshaping)Hyon LimMon, 05 Nov 2012 11:16:45 -0600http://answers.opencv.org/question/3780/