【问题标题】:How can I turn a three channel Mat into a summed up one channel Mat?我怎样才能把一个三通道的垫子变成一个总结的单通道垫子?
【发布时间】:2019-12-04 01:46:17
【问题描述】:

我想将一个 Mat 图像的所有通道添加到一个只有一个 sum-channel 的 Mat 图像中。我试过这样:

    // sum up the channels of the image:
    // 1 .store initial nr of rows/columns
    int initialRows = frameVid1.rows;
    int initialCols = frameVid1.cols;

    // 2. check if matrix is continous
    if (!frameVid1.isContinuous())
    {
        frameVid1 = frameVid1.clone();
    }
    // 3. reshape matrix to 3 color vectors
    frameVid1 = frameVid1.reshape(3, initialRows*initialCols);
    // 4. convert matrix to store bigger values than 255
    frameVid1.convertTo(frameVid1, CV_32F);
    // 5. sum up the three color vectors
    reduce(frameVid1, frameVid1, 1, CV_REDUCE_SUM);
    // 6. reshape to initial size
    frameVid1 = frameVid1.reshape(1, initialRows);
    // 7. convert back to CV_8UC1
    frameVid1.convertTo(frameVid1, CV_8U);

但不知何故,reduce 不会像矩阵维度那样触及颜色通道。有没有别的函数可以总结一下?

还有为什么在步骤 4 中使用 CV_16U.) 不起作用? (我必须在里面放一个 CV_32F)

提前致谢!

【问题讨论】:

    标签: c++ opencv


    【解决方案1】:

    你可以用一行来总结 RGB 通道

    cv::transform(frameVid1, frameVidSum, cv::Matx13f(1,1,1))
    

    您可能需要多一行,因为在应用转换之前,您应该将图像转换为某种适当的类型以避免饱和(我假设CV_32FC3)。 - 输出数组的大小和深度与源相同。

    一些解释:

    cv::transform 可以对每个像素的通道值进行操作。 对于每个像素[u,v] 有第三个参数cv::Matx13f(a, b, c),它执行以下操作:

    frameVidSum[u,v] = frameVid1[u,v].B * a + frameVid1[u,v].G * b + frameVid1[u,v].R * c
    

    通过使用第三个参数cv::Matx13f(1,0,1),您将只对蓝色和红色通道求和。

    cv::transform 太聪明了,你甚至可以使用cv::Matx14f 然后将第四个值添加(偏移)到frameVidSum 中的每个像素。

    【讨论】:

      【解决方案2】:

      每个第 3 个元素(在 RGB 中)都是一种相似的颜色。如果您将每组 3 个元素(R、G 和 B)相加并将其存储在另一个 1 通道矩阵中,它可能会起作用。在存储之前,您应该使用saturate cast 以避免意外结果。所以,我认为更好的方法是使用饱和投射而不是调整你的矩阵。

      【讨论】:

        【解决方案3】:

        查看cv::split() 和cv::add() 函数。

        您可以使用 split 函数将图像拆分为单独的通道,然后使用 add 函数添加图像。但是在使用 add 时要小心,因为添加可能会导致值饱和。您可能必须先转换类型,然后再添加。看看这里:http://answers.opencv.org/question/13769/adding-matrices-without-saturation/

        【讨论】:

          猜你喜欢
          • 2019-01-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-11-14
          • 2020-06-23
          相关资源
          最近更新 更多