繁体   English   中英

如何有效地从 C++ 中的 cv::Mat 图像中提取某些像素?

[英]How to efficiently extract certain pixels from cv::Mat image in C++?

我正在做一些图像处理,我想从灰度图像中提取某些像素值。 我想提取的像素用一个与灰度图像具有相同尺寸的掩码数组来描述。

这在 python 中使用 numpy 数组很容易完成。 例子:

pixels = img[mask != 0]

谁能建议我如何使用 opencv 数据类型 cv::Mat 在 C++ 中以有效的方式执行此操作?

更新

我将提供一个更广泛的例子来澄清我的问题。 假设我有一个名为img的灰度图像,尺寸为 (3,4)。 我还有一个尺寸为 (3,4) 的掩码数组。 我想在对应于掩码数组中非零值位置的位置从img数组中提取值。 如果我们假设掩码数组有 4 个非零元素,那么img数组中的 4 个元素需要被提取(复制)到一个名为pixel的新数组中。

img = np.arange(12).reshape((3,4))
# img = array([[ 0,  1,  2,  3],
#              [ 4,  5,  6,  7],
#              [ 8,  9, 10, 11]])

mask = np.zeros_like(img)
mask[0:2, 1] = 255
mask[1, 2:4] = 255
# mask = array([[  0, 255,   0,   0],
#               [  0, 255, 255, 255],
#               [  0,   0,   0,   0]])

pixels = img[mask != 0]
# pixels = array([1, 5, 6, 7])

我想使用 cv::Mat 数组在 C++ 中实现相同的功能。 我知道这可以使用 for 循环来完成,但我更喜欢更有效的(矢量化)解决方案,如果存在的话。

您必须遍历所有图像像素。 首先,您可以使用带有遮罩的参考图像创建图像:

srcImage.copyTo(dstImage, mask);

您现在可以创建函数来对像素执行某些操作:

//Your function
void doSomething(cv::Point3_<uint8_t> &pixel)
{
    //... in this example you can change value like this: pixel.x = 255 - x means first color channel
}

现在,当您迭代时,您必须检查像素是否等于零。 在 c++ 中,您可以通过多种方式进行迭代:

// .at method: 
// Loop over all rows
for (int r = 0; r < dstImage.rows; r++)
{
    // Loop over all columns
    for (int c = 0; c < dstImage.cols; c++)
    {
        // Obtain pixel
        Point3_<uint8_t> pixel = dstImage.at<Point3_<uint8_t>>(r, c);
        // check if values are zero
        if (pixel.x !=0 && pixel.y !=0 && pixel.z !=0)
        // function
             doSomething(pixel);
        // set result
        dstImage.at<Point3_<uint8_t>>(r, c) = pixel;
    }

}


//with pointers  
// Get pointer to first pixel
Point3_<uint8_t>* pixel = dstImage.ptr<Point3_<uint8_t>>(0, 0);
const Point3_<uint8_t>* endPixel = pixel + dstImage.cols * dstImage.rows;
// Loop over all pixels
for (; pixel != endPixel; pixel++)
{
    // check if values are zero
    if (pixel.x !=0 && pixel.y !=0 && pixel.z !=0)
          doSomething(*pixel);
}


//forEach - utilizes all the cores to apply any function at every pixel - the fastest way
//define Functor
struct Operator
{
    void operator ()(Point3_<uint8_t> &pixel, const int * position) const
    {           
          // check if values are zero
          if (pixel.x !=0 && pixel.y !=0 && pixel.z !=0)
                doSomething(pixel);
    }
};
//execute functor
dstImage.forEach<Point3_<uint8_t>>(Operator());

如果在参考图像上放置蒙版之前没有零值,它将起作用。 如果是,您必须使用 forEach 遍历蒙版图像。 然后你可以使用const int * position参数int x = position[0]; int y = position[1]; int x = position[0]; int y = position[1]; 检查哪些坐标掩码像素等于 0 并且只为它们在参考图像上做一些事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM