Search code examples
c++opencvmat

How to access a 3 dimensional Matrix elements?


How do I index through a 3 dimensional matrix? I have this code and I know that the string inside cycles is wrong. Any suggestions on doing it in proper way.

    Mat frame_;
    cvtColor(frame, frame_, CV_BGR2HSV);
    int size[3] = { capture_box_dim*capture_box_count, capture_box_dim, 3};
    Mat ROI = Mat::zeros (3, size, frame_.type());
    for (int i = 0; i < capture_box_count; i++)
    {
        for (int j = i*capture_box_dim, int k = box_pos_y[i], int l = 0, int t = box_pos_x[i];
                j < i*capture_box_dim + capture_box_dim
             && k < box_pos_y[i] + capture_box_dim 
             && l < capture_box_dim
             && t < box_pos_x[i] + capture_box_dim;
             j++, k++, l++, t++)
        {
            ROI[j][l] = frame_[k][t];
        }
    }

Solution

  • your peace of code is complex but as i understand you like to know how to access all data of a point (i.e. all 3 values). it is simple by using Vec.

    Vec3b intensity = img.at<Vec3b>(y, x);
    uchar blue = intensity.val[0];
    uchar green = intensity.val[1];
    uchar red = intensity.val[2];
    

    the best way to access Mat elements is at<> method. in your code:

    ROI.at<Vec3b>(j,l) = frame_.at<Vec3b>(k,t);
    

    Vec is Vector class. the number after Vec indicates the number of channels. for example if you have an RGB image you have 3 channels. the last character indicates type. the most common vector is Vec3b. here is defined types of vectors:

    typedef Vec<uchar, 2> Vec2b;
    typedef Vec<uchar, 3> Vec3b;
    typedef Vec<uchar, 4> Vec4b;
    
    typedef Vec<short, 2> Vec2s;
    typedef Vec<short, 3> Vec3s;
    typedef Vec<short, 4> Vec4s;
    
    typedef Vec<int, 2> Vec2i;
    typedef Vec<int, 3> Vec3i;
    typedef Vec<int, 4> Vec4i;
    
    typedef Vec<float, 2> Vec2f;
    typedef Vec<float, 3> Vec3f;
    typedef Vec<float, 4> Vec4f;
    typedef Vec<float, 6> Vec6f;
    
    typedef Vec<double, 2> Vec2d;
    typedef Vec<double, 3> Vec3d;
    typedef Vec<double, 4> Vec4d;
    typedef Vec<double, 6> Vec6d;