图像到极坐标

Image to polar co-ordinates

我在将图像转换为极坐标时遇到问题。在 Photoshop 中很容易 :) 所以这对我来说是新领域。

我有以下图片:

最后应该是这样的:

我看过了here,基本了解了,但是对圆的平方还是有点迷惑:

import math
from PIL import Image, ImageDraw


# image size
imgX = 200
imgY = 200

image = Image.new("RGB", (imgX, imgY))
draw = ImageDraw.Draw(image)

#fill with white first
colour = "#ffffff"
box = [0,0, imgX, imgY]
image.paste(colour, box)

# draw line near base
draw.line((0,180, 200, 180), fill="#FF0000", width=2)

print "Line done!"
image.save("line.png", "PNG")

# there's got to be a way to get the current image
# without having to open it up again

im = Image.open("line.png")
rgb_im = im.convert("RGB")

# rectangle to polar coordinates
maxradius = math.sqrt(imgX**2 + imgY**2)/2
rscale = imgX / maxradius
tscale = imgY / (2*math.pi)

for y in range(0, imgY):
    dy = y - imgY/2

    for x in range(0, imgX):
        dx = x - imgX/2
        t = math.atan2(dy,dx)%(2*math.pi)
        r = math.sqrt(dx**2+dy**2)

        r, g, b = rgb_im.getpixel((x, y))
        # this is where it goes wrong
        col = b * 65536 + g * 256 + r
        image.putpixel((x, y), b * 65536 + g * 256 + r

image.save("polar.png", "PNG")

我几乎就在那里,只是对如何重绘图像有点困惑。还有一个警告:由于管理限制,我想避免使用像 Numpy 这样的外部库。

以下代码对我有用。主要变化:

  • line_imagecircle_image 创建了单独的变量。没有理由重新加载图像,你可以重复使用 line_image...

  • tr 将为您提供您想要在线图像中访问的每个对应的 x 和 [=17= 的图像坐标] 在圆形图像中。它们已经存在,您只需有效地使用它们作为索引来获取像素颜色。

  • rscaletscale应用到rt,使得2×pi对应于图像的右边缘。您肯定需要更改 r 的比例才能在输出中看到这个圆圈,或者将线画得更靠近顶部(例如,在第 100 行而不是第 180 行)。

  • 我还包括了对线图像访问的边界检查。

```

import math
from PIL import Image, ImageDraw     
# image size
imgX = 200
imgY = 200

line_image = Image.new("RGB", (imgX, imgY))
draw = ImageDraw.Draw(line_image)

#fill with white first
colour = "#ffffff"
box = [0,0, imgX, imgY]
line_image.paste(colour, box)

# draw line near base
draw.line((0,180, 200, 180), fill="#FF0000", width=2)

print "Line done!"
line_image.save("line.png", "PNG")

circle_image = Image.new("RGB", (imgX, imgY))

# rectangle to polar coordinates
maxradius = math.sqrt(imgX**2 + imgY**2)/2
rscale = imgX / maxradius
tscale = imgY / (2*math.pi)

for y in range(0, imgY):
    dy = y - imgY/2

    for x in range(0, imgX):
        dx = x - imgX/2
        t = math.atan2(dy,dx)%(2*math.pi)*tscale
        r = math.sqrt(dx**2+dy**2)*rscale

        if 0<= t < imgX and 0 <= r < imgY:
            r, g, b = line_image.getpixel((t, r))
            # this is where it goes wrong
            col = b * 65536 + g * 256 + r
            circle_image.putpixel((x, y), col)

circle_image.save("polar.png", "PNG")

```