read image as array - save array as image

asked 2015-12-05 08:09:06 -0500

ggeo gravatar image

updated 2015-12-05 08:14:06 -0500

Hello , I just started to study openCV and I am trying to figure how to properly read the image as array.

First of all , when I am loading the image using imread , what is the type ? Always unsigned char?

So,for example, I am trying to do:

...
Mat  grayImage;
...

unsigned char *myData = grayImage.data;
int width = grayImage.cols;
int height = grayImage.rows;

for(int i = 0; i < height; i++)
{
    for(int j = 0; j < width; j++)
    {
        cout << "Mat[ " << i * width + j << " ] = " << (myData[ i * width + j ]) << "\t";
    }
    cout << endl;
}

I am receiving as output symbols and letters.

Also, if I want to store an array as an image what steps must I follow?

(I forgot to mention that I want to use pointers in order to access data)

edit retag flag offensive close merge delete

Comments

even though you can do cout << grayImage because of unsigned char *myData cout print out chars (symbol and letter) use cast if you want numbers.

At the end to use pointers in order to access data you have to be sure that grayImage is continuous. Check the doc for more information about how to scan images .

pklab gravatar imagepklab ( 2015-12-05 09:12:40 -0500 )edit

@pklab:Thanks for the help.So,the proper way to use pointers in order to access data is (after checking the continuous ) is to use const float* ptr1 = grayImage.ptr<float>(i);in the loop ?And what about accessing the data outside the loop? ( because ptr1 is defined in the loop according to [this] http://docs.opencv.org/3.0.0/d3/d63/c...

ggeo gravatar imageggeo ( 2015-12-05 09:41:53 -0500 )edit

Too many things in the question...

  • imread() outputs uchar matrices as images usually take 0-255 range
  • To save an array as image, if you want to stick to the uchar range, imwrite() is there. But if you have a different type of array (say float) or you just want to save your array preserving it structure, you can also use FileStorage class or use custom functions to save it to .csv files (or even binary files). The search bar of the forum will help you
  • I don't know why you want to use pointers to access data, but as you're new to OpenCV, some insights:
    • Avoid per-element accesses/operations. You will find overloaded optimized functions for common operations
    • Stick with simpler options like iterators to start. You won't probably need the extra speed of pointers
LorenaGdL gravatar imageLorenaGdL ( 2015-12-05 09:59:53 -0500 )edit