gpt4 book ai didi

python - 旋转后的图片看起来像缺少像素

转载 作者:太空狗 更新时间:2023-10-29 21:34:37 26 4
gpt4 key购买 nike

我一直在研究 PIL 和变换矩阵,以了解简单的 2D 图像处理背后的原理。

在我尝试尽可能“低水平”地旋转图像时(也就是说,不使用任何 rotate(degrees) 函数,而是进行数学计算)我决定旋转图像的每个像素使用顺时针旋转矩阵的图像:

enter image description here

旋转很顺利,但图像现在看起来缺少一些像素。

原始图像,绘制在 435x353 黑色背景上:

enter image description here

顺时针旋转 45° 并向右移动 300 像素:

enter image description here

奇怪的是,将图片顺时针旋转 90°(并向右移动 400 像素)时,问题没有出现:

enter image description here

这可能是什么原因造成的?使用 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')

最佳答案

对于每个目标像素,您需要计算源像素,但反之则不行。由于四舍五入,您有几个源像素映射到同一个目标像素。这就是为什么不使用插值实际上无法获得良好的 45° 旋转的原因。我的建议实际上是最近邻插值。

关于python - 旋转后的图片看起来像缺少像素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21637741/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com