8

In OpenCV, I'm able to capture frames using VideoCapture in C++, however, when I try to get the data from a frame and calculate length, it just returns me 0.

Below is my sample code:

VideoCapture cap(0);
for(;;) {
  Mat frame;
  cap >> frame;
  int length = strlen((char*) frame.data); // returns 0
}

As I mentioned above that if I save the frame in a PNG file, I can actually see the image so I'm not able to understand why the data length is coming out to be zero.

Any clue?

Danvil
  • 22,240
  • 19
  • 65
  • 88
pree
  • 2,297
  • 6
  • 37
  • 55
  • 1
    possible duplicate of [Size of Matrix OpenCV](http://stackoverflow.com/questions/14028193/size-of-matrix-opencv) – MattG Apr 03 '14 at 22:16
  • 1
    But how do I calculate length of the buffer from the rows and cols info? Moreover, the above code should also work, isn't it? – pree Apr 03 '14 at 22:38
  • 2
    It's been a while since I've done OpenCV, but strlen is looking for a null character. Are you sure `frame.data` doesn't start with a `'\0'` or `0`? I'm not sure that this is a valid way to tell the buffer size. – Suedocode Apr 03 '14 at 22:49

2 Answers2

14

You can also do:

Mat mat;
int len = mat.total() * mat.elemSize(); // or mat.elemSize1()
Asalle
  • 1,239
  • 19
  • 41
9

The strlen method only works on strings, which are arrays of chars terminated by a special character:

http://www.cplusplus.com/reference/cstring/strlen/

You have cast a Mat type as a char*, so it is not a string.

Building on the solution here, try:

Mat mat;
int rows = mat.rows;
int cols = mat.cols;
int num_el = rows*cols;
int len = num_el*mat.elemSize1();

to get the size of one channel in bytes. Also, use elemSize() if you want all the channels (i.e. you'll get 3 times the value of elemSize1() if the Mat is a 3 channel image).

Take a look here for discussion of the various types Mat can contain:

http://docs.opencv.org/modules/core/doc/basic_structures.html#mat-type

Community
  • 1
  • 1
MattG
  • 1,416
  • 2
  • 13
  • 31