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

OpenCV 影像特效:Twirl Filter(漩渦扭曲效果)實現

     編輯:關於C++

效果描述

Twirl Filter 在圓形區域內產生角度隨半徑非線性旋轉的漩渦效果。中心旋轉角度最大,向邊緣遞減至零,形成螺旋狀幾何變形。

核心演算法

  1. 設定中心 (centreX, centreY)、最大旋轉角度 angle、影響半徑 radius(0 表示自動取短邊一半)。
  2. 對每個輸出像素 (x, y),計算相對中心向量 (dx, dy) 及距離 distance = sqrt(dx²+dy²)。
  3. 若 distance > radius,保持原位。
  4. 否則計算旋轉角度:a = atan2(dy, dx) + angle * (radius - distance) / radius。
    線性衰減:中心 distance=0 旋轉 angle,邊緣 distance=radius 旋轉 0。
  5. 新座標:new_x = cx + distance * cos(a),new_y = cy + distance * sin(a)。
  6. 雙線性插值採樣。

完整 OpenCV C++ 實現

#include <opencv2/opencv.hpp>
#include <cmath>
#include <algorithm>
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());
    src.copyTo(dst); // 初始化為原圖,未變形區域保持原樣

    int w = src.cols, h = src.rows;
    float cx = w * 0.5f, cy = h * 0.5f;
    float radius = 0.0f;
    if (radius == 0) radius = min(w, h) * 0.5f;
    float radius2 = radius * radius;
    float angle = CV_PI / 3; // 60 度最大旋轉

    for (int y = 0; y < h; ++y) {
        for (int x = 0; x < w; ++x) {
            float dx = x - cx, dy = y - cy;
            float dist2 = dx*dx + dy*dy;
            float nx = x, ny = y;

            if (dist2 < radius2 && dist2 > 0) {
                float distance = sqrt(dist2);
                float a = atan2(dy, dx) + angle * (radius - distance) / radius;
                nx = cx + distance * cos(a);
                ny = cy + distance * sin(a);
            }
            // 邊界裁剪
            nx = max(0.0f, min(nx, w - 2.0f));
            ny = max(0.0f, min(ny, h - 2.0f));
            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, "Twirl Effect");
    waitKey(0);
    return 0;
}

參數調整建議

  • angle:正值順時針漩渦,負值逆時針。典型 π/4 ~ π。
  • radius:控制影響範圍。較小值產生局部漩渦,較大值影響全圖。
  • 可改為非線性衰減:(radius - distance)^2 / radius^2 產生更銳利漩渦核心。

效果展示

Twirl Filter 效果圖

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