如何为图像添加漩涡(图像失真)?

How do you add a swirl to an image (image distortion)?

我试图弄清楚如何在照片中制作漩涡,试着到处寻找你对像素做了什么。我在和一个朋友聊天,我们有点谈论使用正弦函数来重定向像素?

假设您使用 4 个参数定义旋流:

  • 漩涡中心的 X 和 Y 坐标
  • 漩涡半径(以像素为单位)
  • 曲折次数

从源图像开始,然后创建应用了漩涡的目标图像。对于每个像素(在目标图像中),您需要根据漩涡调整像素坐标,然后从源图像中读取一个像素。要应用漩涡,请计算出像素与漩涡中心的距离及其角度。然后根据扭曲的数量调整角度,当你离中心越远,它就会逐渐消失,直到你到达漩涡半径时它变成零。使用新角度计算调整后的像素坐标以进行读取。在伪代码中是这样的:

Image src, dest
float swirlX, swirlY, swirlRadius, swirlTwists
for(int y = 0; y < dest.height; y++)
{
    for(int x = 0; x < dest.width; x++)
    {
        // compute the distance and angle from the swirl center:
        float pixelX = (float)x - swirlX;
        float pixelY = (float)y - swirlY;
        float pixelDistance = sqrt((pixelX * pixelX) + (pixelY * pixelY));
        float pixelAngle = arc2(pixelY, pixelX);

        // work out how much of a swirl to apply (1.0 in the center fading out to 0.0 at the radius):
        float swirlAmount = 1.0f - (pixelDistance / swirlRadius);
        if(swirlAmount > 0.0f)
        {
            float twistAngle = swirlTwists * swirlAmount * PI * 2.0;

            // adjust the pixel angle and compute the adjusted pixel co-ordinates:
            pixelAngle += twistAngle;
            pixelX = cos(pixelAngle) * pixelDistance;
            pixelY = sin(pixelAngle) * pixelDistance;
        }
        // read and write the pixel
        dest.setPixel(x, y, src.getPixel(swirlX + pixelX, swirlY + pixelY));
    }
}