How to read some elements of a matrix from disk C++ - c++

I have a code where I'm reading 1024x1024 float matrix from disk then I'm getting some elements of it and doing some process on the new matrix as follows.
// mask is the 1Kx1K matrix that 1/64 element of it are 1 other elements are 0;
// it is a mask for **Mat data**
string filename = "filepath";
Mat data(1024,1024,CV_32F);
readMatrix(filename, data);
Mat smallMat(128,128,CV_32F);
getSmallerMat(data, mask, smallMat);
I read from float Mat from disk and fill smallMat using getSmallerMat(...) which is simply two for loops checking if mask(i,j) == 1, write to next position in smallMat
readMatrix(string fpath,Mat& data){
FILE* fp = fopen(fpath.c_str(),"rb");
if (!fp)perror("fopen");
int size = 1024;
data.create(size,size,CV_32F);
float* buffer= new float[size];
for(int i=0;i<size;++i) {
fread(buffer,sizeof(float),size,fp);
for(int j=0;j<size;++j){
data.at<float>(i,j)=buffer[j];
}
}
fclose(fp);
free(buffer);
}
What I want to do is just reading matrix elements whose corresponding value in mask is equal to 1. My problem is how will I pick (i,j)-th element from the disk.
Reading whole matrix and squeezing it takes 15 ms, I want to make it faster but I couldn't achieve to do it.
Consider this pic is my mask matrix. I want to read only white pixels only.
Thanks,

I am not sure that i understand the question correctly, but are you looking for a method to access data on the hard disk more quickly than via a stream? For finding some specific matrix element (i,j) in your stream you need to read the whole file (in the worst case), i.e. the complexity is linear, this can't be helped.
However, if you actually know the position in the fiel exactly (i.e. if you use a fixed length format for representing your doubles, etc.) seekg
http://www.cplusplus.com/reference/istream/istream/seekg/
should be faster than actually reading all characters until the desired position.
EDIT:
Given the discussion in comments to other answers I want to stress that using some seek in a file stream is O(N), hence multiple seeks for specific element will be way slower than just reading the whole file. I am not aware of a method to access data stored on hard disk in O(1). However, if all you ever need is matrices which are zero outside your mask, you should familiarize yourself with the concept of sparse matrices.
See e.g. https://en.wikipedia.org/wiki/Sparse_matrix and the documentation for your library, e.g. http://www.boost.org/doc/libs/1_39_0/libs/numeric/ublas/doc/matrix_sparse.htm

I am not sure if I have understood your problem or not; but if you want to read i,j th element from a file which contains the only float elements you should be able to get it like below -
float get(int i, int j, int rowsize, FILE * fp) {
float retVal = -1.0f; //-infinity may be?
// if you need restoring the stream pos
long lastPos = ftell(fp);
// ff to i*row + j
fseek(fp , ((i * rowsize) + j) * sizeof(float), SEEK_SET);
fread((unsigned char *)&retVal, sizeof(float), 1, fp);
// restore prevpos
// bla bla bla
return retVal;
}
You should be able to read any file which contains fixed size element very fast using the fseek and some arithmatic from start end or current file pointer. check the fseek documentation for more details.

From your code it appears your matrix is stored in binary as a memory image of the floats. What you want is go directly to the index on the disk where the (i,j) float is. You can compute this position using the following formula: index = i*colWidth+j where colWidth is 1024 in your case. You can use fseek and ftell to move your position and get your position in the file opened by fopen.

Related

Sparse matrix without knowing size

Does Eigen support element insertion into a sparse matrix if the size is not known?
I have a stream of data coming in, and I am attempting to store that sparsely, but I don't know the maximum value of the indices (row/column) of the data ahead of time (I can guess, but not guarantee). Looking at Eigen's insert code, it has an assertion (1130, SparseMatrix.h) that the index that you wish to insert into is <=rows(), <=cols().
Do I really need to wait until I have all the data before I can start using Eigen's sparse matrix code? The design I would have to go for then would require me to wait for all the data, then scanto find the maximum index, which is not ideal for my application. I curently don't need the full matrix to start working - an limited one with the currently available data would be fine.
Please don't close this question unless you have an answer, the linked answer was for dense matrices, not sparse ones, which have different internal storage...
I'm also looking for information on the case where matrix size is not immediately available at run-time, rather than at compile time, and olny for sparse.
The recommendation is still to store the values into a intermediate triplets container and build the sparse matrix at the end. If you don't want to read all the stream... then just read first nnn triplets until your desired condition and then use setFromTriplets() with the partial list of triplets.
But, if you still don't want to read the full matrix to start working, you can guess a size for your matrix and make it grow in case you read a value that can not be stored in your current size using conservativeResize().
#include <Eigen/Sparse>
#include <iostream>
Eigen::SparseMatrix<double> mat;
mat.resize(100,100); //Initial size guess. Could be 1, 10, 1000, etc...
fstream inputStream ("filename.txt", "r"):
while(inputStream)
{
//Read position and value from stream
unsigned i, j;
double v;
inputStream >> i >> j >> v;
//check current size of the matrix and make it grow if necessary
if ( (i >= mat.rows()) || (j >= mat.cols()) )
mat.conservativeResize(std::max(i+1, mat.rows()), std::max(j+1, mat.cols()) );
//store the value in matrix
mat.coeffRef(i,j) = v;
//Insert here your condition to break before of read all the stream
if (mat.nonZeros() > 150 )
break;
}
//Do some clean-up in case you think is necessary
mat.makeCompressed();

How to store an Image as a 1*n floating point vector?

Im trying to obtain a single floating vector called testdata from images obtained via a webcam.Once the images are converted to a single floating vector ,it is passed to a trained Neural Network.To test the network I use the function float CvANN_MLP::predict(const Mat& inputs, Mat& outputs).This function requires an testing sample in the format as follows :-
Floating-point matrix of input vectors, one vector per row.
testdata vector is defined as follows:-
// define testing data storage matrices
//NumberOfTestingSamples is 1 and AttributesPerSample is number of rows *number of columns
Mat testing_data = Mat(NumberOfTestingSamples, AttributesPerSample, CV_32FC1);
To store each row of the image in a CSV Format ,I do the following :-
Formatted row0= format(Image.row(0),"CSV" ); //Get all rows to store in a single vector
Formatted row1= format(Image.row(1),"CSV" ); //Get all rows to store in a single vector
Formatted row2= format(Image.row(2),"CSV" ); //Get all rows to store in a single vector
Formatted row3= format(Image.row(3),"CSV" ); //Get all rows to store in a single vector
I then output all formated rows which were stored in row0 to row3 into a textfile as such:-
store_in_file<<row0<<", "<<row1<<", "<<row2<<", "<<row3<<endl;
This will store the entire Mat on a single line.
The textfile is closed .I reopen the same textfile to extract the data to store into the vector testdata
// if we can't read the input file then return 0
FILE* Loadpixel = fopen( "txtFileValue.txt", "r" );
if(!Loadpixel) // file didn't open
{
cout<<"ERROR: cannot read file \n";
return 0; // all not OK;
}
for(int attribute = 0; attribute < AttributesPerSample; attribute++)
{
fscanf(Loadpixel, "%f,",&colour_value);//Reads a single attribute and stores it in colour_value
testdata.at<float>(0, attribute) = colour_value;
}
This works ,however after a period of time the file doesn't open and displays the Error Message:"ERROR: cannot read file ".There is alot of limitation to this method,unnecessary time take to store in a textfile and then reopen and extract.What is the best way to store an image(Mat) into a single floating point vector similar to testdata.at<float>(0, attribute) ? Or is there a simple way to ensure that the file always opens,basically the correct the problem?
The sane solution is of course to convert the values directly in memory. The whole file intermediate is an incredible kludge, as you suspected.
If you would use standard C++ types such as std::vector, we could provide actual code. The simple algorithm equivalent to your code is to just iterate through your 2D image one pixel at a time, and append each pixel's value to the back of the 1D vector.
However, that's a bad idea for neural network processing of webcam images anyway. If your input shifts down by a single pixel - entirely possible - the whole 1D vector changes. It's therefore advisable to normalize your input first. That may require translating, scaling and rotating the image first.
[edit]
Standard C++ example:
std::vector<std::vector<int>> Image2D;
std::vector<float> Vector1D;
for (auto const& row : Image2D) {
for (auto pixel : row) {
Vector1D.push_back(pixel);
}
}

C++ fwrite access violation when writing image file

I need to append RGB frame to file on each call.
Here is what I do :
size_t lenght=_viewWidth * _viewHeight * 3;
BYTE *bytes=(BYTE*)malloc(lenght);
/////////////// read pixels from OpenGL tex /////////////////////
glBindTexture(GL_TEXTURE_2D,tex);
glGetTexImage(GL_TEXTURE_2D,0,GL_BGR,GL_UNSIGNED_BYTE,bytes);
glBindTexture(GL_TEXTURE_2D,0);
///write it to file :
hOutFile = fopen( outFileName.c_str(), cfg.appendMode ? "ab" : "wb" );
assert(hOutFile!=0);
fwrite(bytes, 1 ,w * h, hOutFile); // Write
fclose(hOutFile);
Somehow I am getting access violation when fwrite gets called.Probably I misunderstood how to use it.
How do you determine _viewWidth and _viewHeight? When reading back a texture you should retrieve them with glGetTexLevelparameteri to retrieve the GL_TEXTURE_WIDTH, and GL_TEXTURE_HEIGHT parameters from the GL_TEXTURE_2D target.
Also the line
fwrite(bytes, 1 ,w * h, hOutFile);
is wrong. What is w, what is h? They never get initialized in the code and are not connected to the other allocations up there. Also if those are width and height of the image, it still lacks the number of elements of a pixel. Most likely 3.
It would make more sense to have something like
int elements = ...; // probably 3
int w = ...;
int h = ...;
size_t bytes_length = w*elements * h;
bytes = malloc(bytes_length)
...
fwrite(bytes, w*elements, h, hOutFile);
Is it caused by bytes?
maybe w * h is not what you think it is.
Is the width ever an odd number or not evenly divisible by 4?
By default OpenGL assumes that a row of pixel data is aligned to a four byte boundary. With RGB/BGR this isn't always the case, and if so you'll be writing beyond the malloc'ed block and clobbering something. Try putting
glPixelStorei(GL_PACK_ALIGNMENT, 1)
before reading the pixels and see if the problem goes away.

Shift vector in thrust

I'm looking at a project involving online (streaming) data. I want to work with a sliding window of that data. For example, say that I want to hold 10 values in my vector. When value 11 comes in, I want to drop value 1, shift everything over, and then place value 11 where value 10 was.
The long way would be something like the following:
int n = 9;
thrust::device_vector<float> val;
val.resize(n+1,0);
// Shift left
for(int i=0; i != n-1; i++){
val[i] = val[i+1];
}
// add the new value to the last position
val[n] = newValue;
Is there a "fast" way to do this with thrust? The project I'm looking at will have around 500 vectors that will need this operation done simultaneously.
Thanks!
As I have said, Ring buffer is what you need. No need to shift there, only one counter and a fixed size array.
Let's think how we may deal with 500 of ring buffers.
If you want to have 500 (let it be 512) sliding windows and process them all on the GPU, then you might pack them into one big 2D texture, where each column is an array of samples for the same moment.
If you're getting new samples for each of the vector at once (I mean one new sample for each 512 buffers at one processing step), then this "ring texture" (like a cylinder) only needs to be updated once (upload the array of new samples at each step) and you need just one counter.
I highly recommend using a different, yet still free, library for this problem. In 4 lines of ArrayFire code, you can do all 500 vectors, as follows:
array val = array(window_width, num_vectors);
val = shift(val, 0, 1);
array newValue = array(1,num_vectors);
val(span,end) = newValue;
I benchmarked against Thrust code for the same and ArrayFire is getting about a 10X speedup over Thrust.
Downside is that ArrayFire is not open source, but it is still free for this sort of problem.
Want you want is simply thrust::copy. You can't do a shift in place in parallel, because you can't guarantee a value is read before it is written.
int n = 9;
thrust::device_vector<float> val_in(n);
thrust::device_vector<float> val_out(n+1);
thrust::copy(val_in.begin() + 1, val_in.end(), val_out.begin());
// add the new value to the last position
val_out[n] = newValue;

Loading a 3D byte array from a .raw file

As in my previous question, I'm interested in loading a .raw file of a volume dataset into a byte array. I think using a 3D byte array would make things easier when indexing the X,Y,Z coordinates, but I'm not sure about the read size that I should use to load the volume. Would this size declaration allow me to index the volume data correctly?
int XDIM=256, YDIM=256, ZDIM=256;
const int size = XDIM*YDIM*ZDIM;
bool LoadVolumeFromFile(const char* fileName) {
FILE *pFile = fopen(fileName,"rb");
if(NULL == pFile) {
return false;
}
GLubyte* pVolume=new GLubyte[XDIM][YDIM][ZDIM];
fread(pVolume,sizeof(GLubyte),size,pFile); // <-is this size ok?
fclose(pFile);
From the code you posted the fread() call appears to be safe, but consider if a 3D byte array is the best choice of a data structure.
I assume you are doing some kind of rendering as you are using GLubyte. And of course to do any rendering you need to access a vertex defined in 3D space. That will lead to:
pVolume[vertIndex][vertIndex][vertIndex]
This will constantly cause your cahce to be thrashed. The memory will be laid out will all the xs first, then all the ys, and then all the zs. Thus, each time you jump from an x to y to z you may hit a cache miss and really slow perf.