2013-04-27 185 views
2

我試圖打印包含我的圖像的cv :: Mat。然而,無論何時我使用cout打印Mat,將一個2D數組打印到我的文本文件中。我只想在一行中打印一個像素。我如何從cv :: Mat打印明線像素。打印cv :: Mat opencv

回答

0

一個通用的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<<", "; }); 

你可以做一些優化,以連續的通道,那麼它可能看起來像

/** 
*@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); 
    } 
} 

這種通用循環讓我很多次,我希望你覺得它有幫助。如果t這裏有 任何錯誤,或者你有更好的主意,請告訴我。

我想爲opencl設計一些通用算法,可惜它不支持 模板,我希望有一天CUDA將成爲開放標準,否則opencl將支持模板。

這適用於任何數量的通道,只要通道類型基於字節,非字節 通道可能不起作用。