Skip to content

include/cvw/algorithms/geometric.hpp

Geometric transformation algorithms. More...

Namespaces

Name
cvw

Detailed Description

Geometric transformation algorithms.

Author: Charliechen114514

Version: 1.0.0

Since: 1.0.0

Date: 2026-05-15

Provides resize, flip, and rotate operations with expected-based error handling.

Source code

cpp

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

namespace cvw {

template <is_pixel_format F>
[[nodiscard]] inline expected<Image<F>, AlgorithmError>
resize(Image<F> img, int width, int height,
       int interpolation = cv::INTER_LINEAR) {
    auto ec = detail::check_non_empty(img);
    if (!ec) {
        return unexpected(ec.error());
    }
    ec = detail::require_positive_dim(width, height);
    if (!ec) {
        return unexpected(ec.error());
    }

    cv::Mat dst;
    cv::resize(img.mat(), dst, cv::Size(width, height), 0, 0, interpolation);
    return Image<F>(std::move(dst));
}

template <is_pixel_format F>
[[nodiscard]] inline expected<Image<F>, AlgorithmError> flip(Image<F> img,
                                                             int axis) {
    auto ec = detail::check_non_empty(img);
    if (!ec) {
        return unexpected(ec.error());
    }

    cv::flip(img.mat(), img.mat(), axis);
    return img;
}

template <is_pixel_format F>
[[nodiscard]] inline expected<Image<F>, AlgorithmError>
rotate(Image<F> img, double angle, bool expand = false) {
    auto ec = detail::check_non_empty(img);
    if (!ec) {
        return unexpected(ec.error());
    }

    cv::Point2f center(img.width() / 2.0f, img.height() / 2.0f);
    auto rot_mat = cv::getRotationMatrix2D(center, angle, 1.0);

    cv::Mat dst;
    if (expand) {
        cv::Rect2f bbox =
            cv::RotatedRect(center, img.mat().size(), angle).boundingRect2f();
        rot_mat.at<double>(0, 2) += bbox.width / 2.0 - center.x;
        rot_mat.at<double>(1, 2) += bbox.height / 2.0 - center.y;
        cv::warpAffine(img.mat(), dst, rot_mat, bbox.size());
    } else {
        cv::warpAffine(img.mat(), dst, rot_mat, img.mat().size());
    }
    return Image<F>(std::move(dst));
}

} // namespace cvw

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

Built with VitePress