Skip to content

include/cvw/details/image_builder_impl.hpp

Implementation details for ImageBuilder and image I/O. More...

Namespaces

Name
cvw
cvw::detail
Internal validation helpers used by algorithm implementations.

Detailed Description

Implementation details for ImageBuilder and image I/O.

Author: Charliechen114514

Version: 1.0.0

Since: 1.0.0

Date: 2026-05-15

Provides the imread flag resolver and ImageBuilder::load definition that reads an image from disk and converts it to the target format.

Source code

cpp

#pragma once
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>

namespace cvw {

namespace detail {

template <is_pixel_format F> constexpr int imread_flag() {
    if constexpr (std::is_same_v<F, Gray> || std::is_same_v<F, Float1>) {
        return cv::IMREAD_GRAYSCALE;
    } else if constexpr (std::is_same_v<F, Gray16>) {
        return cv::IMREAD_ANYDEPTH;
    } else if constexpr (std::is_same_v<F, BGRA> || std::is_same_v<F, RGBA>) {
        return cv::IMREAD_UNCHANGED;
    } else {
        return cv::IMREAD_COLOR;
    }
}

} // namespace detail

template <is_pixel_format format_type> expected<Image<format_type>, LoadError>
ImageBuilder<format_type>::load(std::string_view path) {
    cv::Mat raw =
        cv::imread(std::string{path}, detail::imread_flag<format_type>());
    if (raw.empty()) {
        return unexpected(LoadError::FileOpenFailed);
    }

    cv::Mat converted;

    if constexpr (std::is_same_v<format_type, BGR> ||
                  std::is_same_v<format_type, BGRA> ||
                  std::is_same_v<format_type, Gray> ||
                  std::is_same_v<format_type, Gray16>) {
        converted = std::move(raw);
    } else if constexpr (std::is_same_v<format_type, RGB>) {
        cv::cvtColor(raw, converted, cv::COLOR_BGR2RGB);
    } else if constexpr (std::is_same_v<format_type, RGBA>) {
        cv::cvtColor(raw, converted, cv::COLOR_BGRA2RGBA);
    } else if constexpr (std::is_same_v<format_type, Float1>) {
        raw.convertTo(converted, CV_32FC1, 1.0 / 255.0);
    } else if constexpr (std::is_same_v<format_type, Float3>) {
        raw.convertTo(converted, CV_32FC3, 1.0 / 255.0);
    } else {
        return unexpected(LoadError::UnsupportedConversion);
    }

    return Image<format_type>(std::move(converted));
}

} // namespace cvw

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

Built with VitePress