首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

OpenCV 影像特效:Circle Filter(圓形幾何變換)實現

     編輯:關於C++

效果描述

Circle Filter 將影像極座標映射為圓形區域,產生魚眼/球面投影效果。影像內容被壓縮到以中心為圓心、指定半徑的圓內,圓外區域可填充背景或透明。

核心演算法

  1. 設定圓心 (centreX, centreY)(歸一化)、半徑 radius、高度參數 high、展開角度 spreadAngle。
  2. 對每個輸出像素 (x, y),計算相對圓心向量 (dx, dy)。
  3. 極座標:r = sqrt(dx²+dy²),θ = atan2(-dy, dx)(Y 軸向下)。
  4. 徑向映射:new_y = high * (1 - r/radius)(或類似線性映射),new_x = θ * radius / spreadAngle(角度映射為水平座標)。
  5. 源圖採樣座標 (new_x, new_y) 需轉換為源圖座標系(通常源圖為矩形)。
  6. 雙線性插值採樣。

完整 OpenCV C++ 實現

#include <opencv2/opencv.hpp>
#include <cmath>
using namespace cv;
using namespace std;

void showImage(const Mat& img, const string& name) {
    namedWindow(name, WINDOW_AUTOSIZE);
    imshow(name, img);
}

int main() {
    Mat src = imread("4.jpg");
    if (src.empty()) return -1;
    Mat dst(src.size(), src.type());

    int w = src.cols, h = src.rows;
    float cx = w * 0.5f, cy = h * 1.0f; // 圓心在底部中央
    float radius = 150.0f;
    float high = 200.0f;
    float spreadAngle = CV_PI;

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            float dx = x - cx, dy = y - cy;
            float r = sqrt(dx*dx + dy*dy);
            float theta = atan2(-dy, dx); // 角度範圍 [-π, π]

            // 映射到源圖座標
            float ny = high * (1.0f - r / radius);
            float nx = (theta / spreadAngle) * radius + cx; // 水平置中

            // 邊界處理:超出源圖範圍跳過(保持目標像素為 0/背景)
            if (nx < 0 || nx >= w-1 || ny < 0 || ny >= h-1) continue;

            int x1 = (int)nx, y1 = (int)ny;
            float px = nx - x1, py = ny - y1;

            for (int k = 0; k < 3; ++k) {
                dst.at<Vec3b>(y, x)[k] = saturate_cast<uchar>(
                    (1-px)*(1-py)*src.at<Vec3b>(y1, x1)[k] +
                    px*(1-py)*src.at<Vec3b>(y1, x1+1)[k] +
                    (1-px)*py*src.at<Vec3b>(y1+1, x1)[k] +
                    px*py*src.at<Vec3b>(y1+1, x1+1)[k]
                );
            }
        }
    }
    showImage(dst, "Circle Filter");
    waitKey(0);
    return 0;
}

關鍵參數調整

  • centreY = 1.0 置圓心於影像底部,產生半圓效果;0.5 為全圓置中。
  • spreadAngle = π 覆蓋 180 度;2π 為全圓。
  • high 控制徑向壓縮比例,決定源圖垂直方向如何映射到圓內。

效果展示

Circle Filter 效果圖

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved