I want to use the opencv cv::Mat function push_back to add new rows to a matrix, but I want to precache the size of the matrix so that the data doesn't need to be constantly reallocated. The cv::mat::reserve function has a number of rows parameter, but that implies that you have to specify the number of columns (and data size first). So the code below I assume would give me one empty row at the beginning which I don't want. Is there a proper way to do this using reserve and push_back??
cv::Mat M(1, size_cols, CV_32FC1);
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++)
{
GetInputMatrix(A);
M.push_back(A.row(i));
}
Note: though the example code doesn't show it I'm not sure of the exact size of the final matrix, but I can get a max value size to reserve.
Using an empty mat in the beginning will be just fine. The column number and type will be determined via the first push_back.
cv::Mat M; // empty mat in the beginning
M.reserve(size_rows);
for (int i = 0; i < size_rows; i++) {
GetInputMatrix(A);
M.push_back(A.row(i));
}
Well, according to documentation,
reserve does:
The method reserves space for sz rows. If the matrix already has enough space to store sz rows, nothing happens. If the matrix is reallocated, the first Mat::rows rows are preserved. The method emulates the corresponding method of the STL vector class.
That being said, as long as you don't that huge amount of data to store, nothing will happen.
Related
I have a video and for each frame, I am dividing into equally sized squares. Each video will have fixed frame dimensions, so the number of squares per video will not change (but different videos with different frame size will change, so the code must be dynamic).
I am trying to loop through each frame, and then loop through each square, and insert the square index and the square matrix into a dictionary. After the first frame, I want to append the square matrix to the vector value at its corresponding key. My code so far:
// let's assume list_of_squares is a vector that holds the Mat values for each square per frame
// also assuming unordered_map<int, vector<Mat>> fixedSquaredict; is declared in a .hpp file and already exists
for (int i=0; i<list_of_squares.size(); i++) {
if (i=0) {
fixedSquaredict.insert({i, list_of_squares[i]});
}
else {
fixedSquaredict[i].push_back(list_of_squares[i]);
}
What I am confused about is this line:
fixedSquaredict.insert({i, list_of_squares[i]});
This line initializes the proper number of keys, but how do I insert the Mat value into the vector<Mat> structure for the first time, so I can then push_back to it in subsequent iterations?
I want the result to be something like this:
// assuming list_of_squares.size() == 2 in this example and it loops through 2 frames
list_of_squares = ((0, [mat1, mat2]),
(1, [mat1, mat2]))
You don't need to do anything, and you don't need the insert call at all. The following will do everything you need:
for (size_t i = 0; i < list_of_squares.size(); ++i) {
fixedSquaredict[i].push_back(list_of_squares[i]);
}
std::unordered_map::operator[] will default-construct a new value if none with that key exists, so the first time a new value of i is encountered it will default-construct a new std::vector<Mat>, which you can then append the first value to.
Side note, using std::unordered_map<int, SomeType> for a contiguous sequence of keys is a bit odd. You've essentially created a less efficient version of std::vector at that point.
So I'm working on a small math library for fun and I'm having a little bit of an issue with this vector. This method is for transposing a matrix, swapping rows for columns and vice versa. It performs this correctly. However, there's something strange going on. From my input of a 3 row x 2 column matrix, the transposition should come back as 2x3, which it does. The problem is the vector is coming back as a size of 4 instead of 2, despite being set to 2 in the method. I've tested it at various points leading up to and after. The size of the vector only changes to 4 once it has called #transpose. It's prepending two vectors of size 0 before the answer (resulting matrix vector). Any ideas as to how? I'm not familiar enough with c++ to know of any quirks.
Matrix Matrix::transpose() {
vector<vector<float>> result;
result.resize(columns);
for (int col = 0; col < columns; col++) {
vector<float> data;
data.resize(rows);
for (int row = 0; row < rows; row++) {
data[row] = vec[row][col];
}
result.push_back(data);
}
return Matrix(result);
}
The code first resizes result, and then appends to it in a loop using push_back. This causes the vector to be resized twice and end up with twice the intended size.
Since the code intends to set the size in advance, the correct fix is to change the push_back line to result[col] = data.
I have got a vector containing contours of an image. The code looks like this:
cv::Mat img = cv::imread ("whatever");
cv::Mat edges;
double lowThresh = 100, highThresh = 2*lowThresh;
Canny(img, edges, lowThresh, highThresh);
std::vector<std::vector<cv::Point>> contourVec;
std::vector<cv::Vec4i> hierarchy;
int mode = CV_RETR_LIST;
int method = CV_CHAIN_APPROX_TC89_KCOS;
findContours(edges, contourVec, hierarchy, mode, method);
What I now would like to do is to transform these points. I therefore created another vector, which shall have the same structure as the other one, just with Point3delements instead of Point. At the moment, I do it like this:
std::vector<std::vector<cv::Point3d>> contour3DVec(contourVec.size());
for (int i = 0; i < contourVec.size(); i++)
contour3DVec[i].resize(contourVec[i].size());
But I'm not sure whether that is really the best way to do it, as I don't know how resize()is actually working (e.g. in the field of memory location).
Does anybody have an idea whether there is a faster and/or "smarter" way to solve this? Thanks in advance.
Given that you surely want to do something with the contours afterwards, the resizing probably won't be a performance hotspot in your Program.
Vectors in c++ are usually created with a bit of slack to grow. They may take up to double their current size in memory.
If you resize a vector it will first check if the resizing will fit in the reserved memory.
If that's the case the resizing is free.
Otherwise new memory (up to double the new size) will be reserved and the current vector content moved there.
As your vectors are empty in the beginning, they will have to reserve new memory anyway, so (given a sane compiler and standard library) it would be hard to beat your Implementation speed wise.
if you want 3d points, you'll have to create them manually, one by one:
std::vector<std::vector<cv::Point3d>> contour3DVec(contourVec.size());
for (size_t i = 0; i < contourVec.size(); i++)
{
for (size_t j = 0; j < contourVec[i].size(); j++)
{
Point p = contourVec[i][j];
contour3DVec[i].push_back( Point3d(p.x, p.y, 1) );
}
}
I have a 2D matrix and I want to copy its values to a 1D array vertically in an efficient way as the following way.
Matrice(3x3)
[1 2 3;
4 5 6;
7 8 9]
myarray:
{1,4,7,2,5,8,3,6,9}
Brute force takes 0.25 sec for 1000x750x3 image. I dont want to use vector because I give myarray to another function(I didnt write this function) as input. So, is there a c++ or opencv function that I can use? Note that, I'm using opencv library.
Copying matrix to array is also fine, I can first take the transpose of the Mat, then I will copy it to array.
cv::Mat transposed = myMat.t();
uchar* X = transposed.reshape(1,1).ptr<uchar>(0);
or
int* X = transposed.reshape(1,1).ptr<int>(0);
depending on your matrix type. It might copy data though.
You can optimize to make it more cache friendly, i.e. you can copy blockwise, keeping track of the positions in myArray, where the data should go to. The point is, that you brute force approach will most likely make each access to the matrix being off-cache, which has a tremendous performance impact. Hence it is better to copy vertical/horizontal taking the cache line size into account.
See the idea bbelow (I didn't test it, so it has most likely bugs, but it should make the idea clear).
size_t cachelinesize = 128/sizeof(pixel); // assumed cachelinesize of 128 bytes
struct pixel
{
char r;
char g;
char b;
};
array<array<pixel, 1000>, 750> matrice;
vector<pixel> vec(1000*750);
for (size_t row = 0; row<matrice.size; ++row)
{
for (size_t col = 0; col<matrice[0].size; col+=cachelinesize)
{
for (size_t i = 0; i<cachelinesize; ++i)
{
vec[row*(col+i)]=matrice[row][col+i]; // check here, if right copy order. I didn't test it.
}
}
}
If you are using the matrix before the vertical assignment/querying, then you can cache the necessary columns when you hit each one of the elements of columns.
//Multiplies and caches
doCalcButCacheVerticalsByTheWay(myMatrix,calcType,myMatrix2,cachedColumns);
instead of
doCalc(myMatrix,calcType,myMatrix2); //Multiplies
then use it like this:
...
tmpVariable=cachedColumns[i];
...
For example, upper function multiplies the matrix with another one, then when the necessary columns are reached, caching into a temporary array occurs so you can access elements of it later in a contiguous order.
I think Mat::reshape is what you want. It does not copying data.
I have a fairly simple question: how to take one row of cv::Mat and get all the data in std::vector? The cv::Mat contains doubles (it can be any simple datatype for the purpose of the question).
Going through OpenCV documentation is just very confusing, unless I bookmark the page I can not find a documentation page twice by Googling, there's just to much of it and not easy to navigate.
I have found the cv::Mat::at(..) to access the Matrix element, but I remember from C OpenCV that there were at least 3 different ways to access elements, all of them used for different purposes... Can't remember what was used for which :/
So, while copying the Matrix element-by-element will surely work, I am looking for a way that is more efficient and, if possible, a bit more elegant than a for loop for each row.
It should be as simple as:
m.row(row_idx).copyTo(v);
Where m is cv::Mat having CV_64F depth and v is std::vector<double>
Data in OpenCV matrices is laid out in row-major order, so that each row is guaranteed to be contiguous. That means that you can interpret the data in a row as a plain C array. The following example comes directly from the documentation:
// compute sum of positive matrix elements
// (assuming that M is double-precision matrix)
double sum=0;
for(int i = 0; i < M.rows; i++)
{
const double* Mi = M.ptr<double>(i);
for(int j = 0; j < M.cols; j++)
sum += std::max(Mi[j], 0.);
}
Therefore the most efficient way is to pass the plain pointer to std::vector:
// Pointer to the i-th row
const double* p = mat.ptr<double>(i);
// Copy data to a vector. Note that (p + mat.cols) points to the
// end of the row.
std::vector<double> vec(p, p + mat.cols);
This is certainly faster than using the iterators returned by begin() and end(), since those involve extra computation to support gaps between rows.
From the documentation at here, you can get a specific row through cv::Mat::row, which will return a new cv::Mat, over which you can iterator with cv::Mat::begin and cv::Mat::end. As such, the following should work:
cv::Mat m/*= initialize */;
// ... do whatever...
cv::Mat first_row(m.row(0));
std::vector<double> v(first_row.begin<double>(), first_row.end<double>());
Note that I don't know any OpenCV, but googling "OpenCV mat" led directly to the basic types documentation and according to that, this should work fine.
The matrix iterators are random-access iterators, so they can be passed to any STL algorithm, including std::sort() .
This is also from the documentiation, so you could actually do this without a copy:
cv::Mat m/*= initialize */;
// ... do whatever...
// first row begin end
std::vector<double> v(m.begin<double>(), m.begin<double>() + m.size().width);
To access more than the first row, I'd recommend the first snippet, since it will be a lot cleaner that way and there doesn't seem to be any heavy copying since the data types seem to be reference-counted.
You can also use cv::Rect
m(cv::Rect(0, 0, 1, m.cols))
will give you first row.
matrix(cv::Rect(x0, y0, len_x, len_y);
means that you will get sub_matrix from matrix whose upper left corner is (x0,y0) and size is (len_x, len_y). (row,col)
I think this works,
an example :
Mat Input(480, 720, CV_64F, Scalar(100));
cropping the 1st row of the matrix:
Rect roi(Point(0, 0), Size(720, 1));
then:
std::vector<std::vector<double> > vector_of_rows;
vector_of_rows.push_back(Input(roi));