opencv - 打印 cv::Mat opencv

标签 opencv image-processing

我正在尝试打印包含我的图像的 cv::Mat。然而,每当我使用 cout 打印 Mat 时,一个二维数组打印到我的文本文件中。我只想在一行中打印一个像素。我如何从 cv::Mat 打印行像素。

最佳答案

一个通用的 for_each 循环,你可以用它来打印你的数据

/**
 *@brief implement details of for_each_channel, user should not use this function
 */
template<typename T, typename UnaryFunc>
UnaryFunc for_each_channel_impl(cv::Mat &input, int channel, UnaryFunc func)
{
    int const rows = input.rows;
    int const cols = input.cols;
    int const channels = input.channels();
    for(int row = 0; row != rows; ++row){
        auto *input_ptr = input.ptr<T>(row) + channel;
        for(int col = 0; col != cols; ++col){
            func(*input_ptr);
            input_ptr += channels;
        }
    }

    return func;
}

像这样使用

for_each_channel_impl<uchar>(input, 0, [](uchar a){ std::cout<<(size_t)a<<", "; });

你可以对连续 channel 做一些优化,那么它可能看起来像

/**
 *@brief apply stl like for_each algorithm on a channel
 *
 * @param
 *  T : the type of the channel(ex, uchar, float, double and so on)
 * @param
 *  channel : the channel need to apply for_each algorithm
 * @param
 *  func : Unary function that accepts an element in the range as argument
 *
 *@return :
 *  return func
 */
template<typename T, typename UnaryFunc>
inline UnaryFunc for_each_channel(cv::Mat &input, int channel, UnaryFunc func)
{
    if(input.channels() == 1 && input.isContinuous()){
        return for_each_continuous_channels<T>(input, func);
    }else{
        return for_each_channel_impl<T>(input, channel, func);
    }
}

这种通用循环为我节省了很多时间,希望对您有所帮助。如果有 任何错误,或者您有更好的想法,请告诉我。

我也想为opencl设计一些通用算法,遗憾的是它不支持 template,希望有一天CUDA成为开放标准,或者opencl支持template。

这适用于任意数量的 channel ,只要 channel 类型基于字节,非字节 channel 可能无法正常工作。

关于opencv - 打印 cv::Mat opencv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16249325/

相关文章:

image-processing - 在此分析的基础上对图像进行分析和转换以获得更好的OCR结果

ruby - 寻找纯 Ruby 的图像处理库

c# - 两幅图像之间的差异

c++ - 该程序已退出,代码为 0 (0x0)。 C++

java - 从矩形构造椭圆

python - 找到最大的轮廓——OpenCV、Python——出现错误

旋转窗口不适合图像后的 Python 2.7.3 + OpenCV 2.4

c++ - 训练分类器的时间

Python OpenCV 活体人脸检测裁剪保存

image-processing - glGetTexImage 返回全黑纹理