Size of Matrix OpenCV

后端 未结 5 928
遇见更好的自我
遇见更好的自我 2020-12-07 11:36

I know this might be very rudimentary, but I am new to OpenCV. Could you please tell me how to obtain the size of a matrix in OpenCV?. I googled and I am still searching, bu

相关标签:
5条回答
  • 2020-12-07 12:18

    For 2D matrix:

    mat.rows – Number of rows in a 2D array.

    mat.cols – Number of columns in a 2D array.

    Or: C++: Size Mat::size() const

    The method returns a matrix size: Size(cols, rows) . When the matrix is more than 2-dimensional, the returned size is (-1, -1).

    For multidimensional matrix, you need to use

    int thisSizes[3] = {2, 3, 4};
    cv::Mat mat3D(3, thisSizes, CV_32FC1);
    // mat3D.size tells the size of the matrix 
    // mat3D.size[0] = 2;
    // mat3D.size[1] = 3;
    // mat3D.size[2] = 4;
    

    Note, here 2 for z axis, 3 for y axis, 4 for x axis. By x, y, z, it means the order of the dimensions. x index changes the fastest.

    0 讨论(0)
  • 2020-12-07 12:20

    A complete C++ code example, may be helpful for the beginners

    #include <iostream>
    #include <string>
    #include "opencv/highgui.h"
    
    using namespace std;
    using namespace cv;
    
    int main()
    {
        cv:Mat M(102,201,CV_8UC1);
        int rows = M.rows;
        int cols = M.cols;
    
        cout<<rows<<" "<<cols<<endl;
    
        cv::Size sz = M.size();
        rows = sz.height;
        cols = sz.width;
    
        cout<<rows<<" "<<cols<<endl;
        cout<<sz<<endl;
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-07 12:20

    If you are using the Python wrappers, then (assuming your matrix name is mat):

    • mat.shape gives you an array of the type- [height, width, channels]

    • mat.size gives you the size of the array

    Sample Code:

    import cv2
    mat = cv2.imread('sample.png')
    height, width, channel = mat.shape[:3]
    size = mat.size
    
    0 讨论(0)
  • 2020-12-07 12:38
    cv:Mat mat;
    int rows = mat.rows;
    int cols = mat.cols;
    
    cv::Size s = mat.size();
    rows = s.height;
    cols = s.width;
    

    Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.

    0 讨论(0)
  • 2020-12-07 12:39

    Note that apart from rows and columns there is a number of channels and type. When it is clear what type is, the channels can act as an extra dimension as in CV_8UC3 so you would address a matrix as

    uchar a = M.at<Vec3b>(y, x)[i];
    

    So the size in terms of elements of elementary type is M.rows * M.cols * M.cn

    To find the max element one can use

    Mat src;
    double minVal, maxVal;
    minMaxLoc(src, &minVal, &maxVal);
    
    0 讨论(0)
提交回复
热议问题