我在将图像转换为极坐标时遇到问题。在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_image
和circle_image
创建了单独的变量。没有理由重新加载图像,你可以重用line_image
...t
和r
将为您提供想要在线图像中访问圆形图像中每个对应的x
和y
的图像坐标。他们已经在那里,你只需要有效地使用它们作为索引来获取像素颜色。rscale
和tscale
应用于r
和t
,使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")
```