モノクロ変換

#include <iostream>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <boost/range/algorithm.hpp>
#include <boost/fusion/include/vector.hpp>
#include <boost/fusion/include/vector_tie.hpp>
#include <boost/fusion/include/algorithm.hpp>

namespace fusion = boost::fusion;

typedef fusion::vector<uchar, uchar, uchar> color_t;

template <class T>
boost::iterator_range<cv::MatIterator_<T> > mat_range(cv::Mat& mat)
{
    return boost::make_iterator_range(mat.begin<T>(), mat.end<T>());
}

void monochrome(color_t& pix)
{
    uchar g, b, r;
    fusion::vector_tie(g, b, r) = pix;

    const float f = static_cast<float>(r) * 0.587f +
                    static_cast<float>(g) * 0.114f +
                    static_cast<float>(b) * 0.299f;

    fusion::for_each(pix, [=](uchar& x) {
        x = static_cast<uchar>(f);
    });
}

int main()
{
    cv::Mat image = cv::imread("belle.jpg");
    if (image.empty()) {
        std::cout << "load error" << std::endl;
        return 1;
    }

    boost::for_each(mat_range<color_t>(image), monochrome);

    cv::imwrite("out.png", image);
}

balle.jpg

out.png


修正履歴:
2010/09/30 17:14 : RGBの順番が逆だったので修正