Skip to content

include/cvw/algorithms/color.hpp

Color space conversion algorithms. More...

Namespaces

Name
cvw

Detailed Description

Color space conversion algorithms.

Author: Charliechen114514

Version: 1.0.0

Since: 1.0.0

Date: 2026-05-15

Provides functions for converting between BGR, RGB, Gray, and YUYV pixel formats. All functions return expected<T, AlgorithmError> for exception-free error handling.

Source code

cpp

#pragma once
#include "detail.hpp"
#include <opencv2/imgproc.hpp>

namespace cvw {

[[nodiscard]] inline expected<Image<Gray>, AlgorithmError>
to_gray(Image<BGR> img) {
    if (img.empty()) {
        return unexpected(AlgorithmError::EmptyInput);
    }
    cv::Mat dst;
    cv::cvtColor(img.mat(), dst, cv::COLOR_BGR2GRAY);
    return Image<Gray>(std::move(dst));
}

[[nodiscard]] inline expected<Image<Gray>, AlgorithmError>
to_gray(Image<RGB> img) {
    if (img.empty()) {
        return unexpected(AlgorithmError::EmptyInput);
    }
    cv::Mat dst;
    cv::cvtColor(img.mat(), dst, cv::COLOR_RGB2GRAY);
    return Image<Gray>(std::move(dst));
}

[[nodiscard]] inline expected<Image<Gray>, AlgorithmError>
to_gray(ImageView<BGR> view) {
    if (view.empty()) {
        return unexpected(AlgorithmError::EmptyInput);
    }
    cv::Mat src(view.height(), view.width(), CV_8UC3,
                const_cast<uint8_t*>(view.data()),
                view.stride() * sizeof(uint8_t));
    cv::Mat dst;
    cv::cvtColor(src, dst, cv::COLOR_BGR2GRAY);
    return Image<Gray>(std::move(dst));
}

[[nodiscard]] inline expected<Image<BGR>, AlgorithmError>
to_bgr(Image<Gray> img) {
    if (img.empty()) {
        return unexpected(AlgorithmError::EmptyInput);
    }
    cv::Mat dst;
    cv::cvtColor(img.mat(), dst, cv::COLOR_GRAY2BGR);
    return Image<BGR>(std::move(dst));
}

[[nodiscard]] inline expected<Image<Gray>, AlgorithmError>
yuyv_to_gray(ImageView<YUYV> view) {
    if (view.empty()) {
        return unexpected(AlgorithmError::EmptyInput);
    }

    int w = view.width();
    int h = view.height();
    Image<Gray> out(w, h);

    for (int row = 0; row < h; ++row) {
        const uint8_t* src_row = view.data() + row * view.stride();
        uint8_t* dst_row = out.data() + row * out.stride();
        for (int col = 0; col < w; col += 2) {
            int idx = col * 2;
            dst_row[col] = src_row[idx];
            if (col + 1 < w) {
                dst_row[col + 1] = src_row[idx + 2];
            }
        }
    }
    return out;
}

} // namespace cvw

Updated on 2026-05-17 at 13:22:38 +0000

Built with VitePress