首页 > 解决方案 > 使用指针将像素强度分配给未初始化的 Mat 矩阵

问题描述

我尝试在 OpenCV 的矩阵中提取感兴趣区域 (ROI)。它可以很容易做到cv:Rect,例如,im_roi = im(Rect(x,y, width, height))。但我更喜欢使用指针直接从内存中获取数据,这可能更有效。下面是我的代码:

Mat im_roi; //the desired matrix holding ROI of im, uninitialized
uchar* im_roi_data = im_roi.data;
uchar* im_data = im.data;

int xstart = x;
int xend = xstart + width;
int ystart = y;
int yend = ystart + height;


for(ii=ystart; ii<yend; ii++)
{
   for(jj=xstart; jj<xend; jj++) //the typo 'jj<xstart' was corrected 
   {
        *im_roi_data++ = *im_data++;
        *im_roi_data++ = *im_data++;
        *im_roi_data++ = *im_data++;
    }
im_data +=3*(im.cols-width);
}

然而,上面的 for 循环代码不会继续。我觉得问题可能是由于未初始化的im_roi.

标签: c++opencv

解决方案


我认为你的第二个for循环需要是:

for(jj=xstart; jj<xend; jj++)

推荐阅读