【发布时间】:2014-02-08 05:12:01
【问题描述】:
我正在使用 PIL 和转换矩阵来了解简单的 2D 图像处理背后的原理。
在我尝试尽可能“低级”旋转图像(即不使用任何rotate(degrees) 函数,而是进行数学运算)时,我决定使用顺时针旋转矩阵旋转图像的每个像素:
旋转正常,但图像现在看起来缺少一些像素。
原始图像,绘制在 435x353 黑色背景上:
顺时针旋转 45° 并向右移动 300 像素:
奇怪的是,将图片顺时针旋转 90°(并向右移动 400 像素)时不会出现此问题:
这可能是什么原因造成的?使用Image.Image.rotate 工作得很好,所以我想问题出在我的代码上。值得一提的是,原图是透明背景,上传到这里时压缩丢失了。但是,我对 jpeg(非透明)图像做了完全相同的操作,结果是一样的。
用于进行旋转的代码:
import Image, ImageDraw
from scipy import misc
import math
WHITE = (255,255,255)
BLACK = (0,0,0)
W, H = 435, 353
im = Image.new('RGBA', (W, H), BLACK)
draw = ImageDraw.Draw(im)
bitmap = misc.imread('Image.png')
def affine_t(x, y, a, b, c, d, e, f):
"""Returns ((a, b), (c, d))*((x), (y)) + ((e), (f))."""
return a*x + b*y + e, c*x + d*y + f
def crotate(x, y, r):
"""Rotate (x, y) clockwise by r radians."""
# And move 300 px to the right for this example
return affine_t(
x, y, math.cos(-r), math.sin(-r), -math.sin(-r), math.cos(-r), 300, 0
)
x, y = 0, 0
angle = math.pi/4
for row in bitmap:
for pt in row:
draw.point([crotate(x, y, angle),],fill=tuple(pt))
x+= 1
x = 0
y += 1
im.save('out.png')
【问题讨论】:
-
如果你深入研究 Pillow,你会看到它是如何做到的(主要是在 C 中以提高速度;中等大小的图像很容易成为百万字节的数组)这是 generic 和 Affine transform (据说更快,我不知道数学)函数。
-
+1 用于“东方”手表
-
您可能会发现 skimage 中的变形功能对实验很有用:scikit-image.org/docs/dev/auto_examples/applications/…
skimage.transform的 API 记录在这里:scikit-image.org/docs/0.9.x/api/skimage.transform.html
标签: python image image-processing matrix python-imaging-library