3

I am beginning to learn OpenCV and am having a bit of trouble with some basic operations. So, I can read a video file as follows:

cv::VideoCapture cap("media.avi");
cv::Mat imgNew;
while (cap.read(imgNew)) {
}

Now, I have another function that has the following signature:

template<class T> 
bool get_estimate(const T * image_data, int num_pixels)

Now, this takes the image data as this linear array of type const T where T in this case could be unsigned char and the num_pixels is the number of pixels in the image.

Can someone tell me how I can use this cv::Mat type with this method. I am hoping there is some easy way to get the underlying array and its type without copying the data into a temporary array but I am not sure. I can always assume that the video image being read is always converted to grayscale.

Angie Quijano
  • 4,167
  • 3
  • 25
  • 30
Luca
  • 10,458
  • 24
  • 107
  • 234
  • Is this similar? http://stackoverflow.com/questions/20980723/convert-mat-to-vector-float-and-vectorfloat-to-mat-in-opencv – a-Jays Oct 06 '14 at 05:26
  • The problem is that the matrix to array conversion is with copying. I was wondering if there is a way to do it without copying.. – Luca Oct 06 '14 at 07:53

1 Answers1

2

The Mat class in OpenCV has a uchar *data member which can be used to access the underlying data. OpenCV Mat.

Mat myImg;                       //assume single channel 2D matrix.
unsigned char *p;
p = myImg.data;
for( unsigned int i=0; i< myImg.cols*myImg.rows; i++ )
    std::cout<< p[i];

Cast p[i] to suitable type.

a-Jays
  • 1,182
  • 9
  • 20
  • This is not correct . If the image is packed (has extra data at the end of each row) then the size will be smaller than the actual data size. In the above example this would just mean that not all the data is printed; but if you tried to allocate a buffer using the code above, the buffer would be too small. For a correct answer see https://stackoverflow.com/a/26441073/638048. – Richard Whitehead May 11 '22 at 12:38