How to Access rows and columns of Vector<Mat> Images on Open cv for Android?

23,555

Solution 1

Mat m;
m.row(i);
m.col(i);

ref: http://opencv.willowgarage.com/wiki/Welcome?action=AttachFile&do=get&target=opencv_cheatsheet.pdf

edit: the following works and produces expected output. perhaps you should describe your errors?

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace cv;
using namespace std;
int main( int argc, char** argv )
{
    vector<Mat> vectors;
    Mat img1 = imread( "C:/test/1.jpg");
    Mat img2 = imread( "C:/test/2.jpg");
    vectors.push_back(img1);
    vectors.push_back(img2);
    cout<<vectors[0].rows<<endl;
    cout<<vectors[0].cols<<endl;
    cin.ignore(1);
    return 0;
}    

Solution 2

The members rows and cols tell you the number of rows and cols the matrix has. To access them, you can use at:

// let's assume your image is CV_8U, so that it is accessed with unsigned char
cv::Mat m = ...;

for(int r = 0; r < m.rows; ++r)
{
  for(int c = 0; c < m.cols; ++c)
  {
    char byte = m.at<unsigned char>(r, c);
    ...
  }
}

You can also save some calls to at and access data by pointer for every row:

// let's assume your image is CV_8U, so that it is accessed with unsigned char
cv::Mat m = ...;

for(int r = 0; r < m.rows; ++r)
{
  const unsigned char *p = m.ptr<unsigned char>();
  for(int c = 0; c < m.cols; ++c, ++p)
  {
    char byte = *p;
    ...
  }
}

If the matrix is continuous in memory, you can get the pointer just once:

// let's assume your image is CV_8U, so that it is accessed with unsigned char
cv::Mat m = ...;

assert(m.isContinuous());

const unsigned char *p = m.ptr<unsigned char>();

for(int r = 0; r < m.rows; ++r)
{
  for(int c = 0; c < m.cols; ++c, ++p)
  {
    char byte = *p;
    ...
  }
}

Solution 3

All the suggestion above are not helping so i decided to create a temp variable with Mat data type and copy the 0th index of the vector to Mat temp and access the rows and columns of temp as temp.cols and temp.rows.Thanks for trying to help me though.

Share:
23,555
Sisay
Author by

Sisay

Updated on August 29, 2020

Comments

  • Sisay
    Sisay over 3 years

    I was going through some code on open cv using Android.Can any one show me how I am gonna access the rows and columns of a vector Mat of image?Its declared and the columns and rows are accessed as given below but i am having errors like and .

    vector<Mat> images;//Vector of Mat image declared
    ...
    int im_width = images[0].cols;//its trying to access column of images matrix
    int im_height = images[0].rows;//trying to access rows of Mat images
    

    If this is not the right way to access the columns and rows of a vector Image, then what is it? When it says images[0] its trying to access the index 0 of the vector of Mat images.I am not sure if this is right or not.