python - 在python中调整图像大小算法

标签 python algorithm python-3.x image-resizing

所以,我正在通过 this tutorial 学习我自己的 python我坚持练习 13,它说:

编写一个函数来统一缩小或放大图像。您的函数应该使用图像和比例因子。要缩小图像,比例因子应介于 0 和 1 之间,要放大图像,比例因子应大于 1。

这不是关于 PIL 的问题,而是要询问使用哪种算法,以便我自己编写代码。

我发现了一些类似的问题,例如 this ,但我不知道如何将其翻译成 python。

如有任何帮助,我们将不胜感激。

我是这样的:

import image

win = image.ImageWin()
img = image.Image("cy.png")

factor = 2

W = img.getWidth()
H = img.getHeight()

newW = int(W*factor)
newH = int(H*factor)

newImage = image.EmptyImage(newW, newH)

for col in range(newW):
    for row in range(newH):
        p = img.getPixel(col,row)
        newImage.setPixel(col*factor,row*factor,p)

newImage.draw(win)

win.exitonclick()

我应该在函数中执行此操作,但现在这并不重要。函数的参数是(图像,因子)。您可以在 ActiveCode 中的 OP 教程中尝试。它制作了一个带有空列的拉伸(stretch)图像:。

最佳答案

如图所示,您的代码对于所谓的最近邻调整大小简单有效,除了一个小错误:

    p = img.getPixel(col/factor,row/factor)
    newImage.setPixel(col,row,p)

编辑:因为您要将浮点坐标发送到 getPixel 中,所以您不限于最近邻 - 您可以在内部实现任何您想要的插值算法。最简单的做法是将坐标截断为 int,这将导致当 factor 大于 1 时复制像素,或者当 factor 时跳过像素> 小于 1。

关于python - 在python中调整图像大小算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12447549/

相关文章:

python - 计算Python中有值(value)的列数

python - 如何安装requirements.txt pip错误->由于OSError : [Errno 2] No such file or directory而无法安装软件包

algorithm - 最大化矩阵中 "non-overlapping"数字的总和

algorithm - 计算运费时处理太多情况的最简单方法是什么?

c++ - 使用分区技术快速排序

python - 如何在 C 函数中访问 python 变量的数据? (参数类型 : void *)

python - 将 Python 包部署到 AWS Lambda 时出错

python - Windows 上的 GeoDjango : "Could not find the GDAL library"/ "OSError: [WinError 126] The specified module could not be found"

python - 如何将同一行附加到列的每个元素,创建一个二维数组?

python - 如何在pygame中生成随机矩形并使它们像飞扬的小鸟一样移动?