gpt4 book ai didi

python - 使用 PIL 将多个图像转换为其负片

转载 作者:行者123 更新时间:2023-12-02 20:35:52 24 4
gpt4 key购买 nike

我想读取文件夹中的所有图像并将它们转换为同一图像的底片

# Import library to work with Images
from PIL import Image

# Make negative pixel
def negatePixel(pixel):
return tuple([255-x for x in pixel])

#img_dir = "" # Enter Directory of all images

for i in range(1,130):
# Original Image
img = []
img = Image.open(str(i) + '.jpg')
# New clear image
new_img = Image.new('RGB', img.size)

# Get pixels from Image
data = img.getdata()
# Create map object consists of negative pixels
new_data = map(negatePixel, data)

# Put negative pixels into the new image
new_img.putdata(list(new_data))
# Save negative Image
new_img.save(str(i) + 'neg.jpg')

print ('saved image' + str(i))

我收到此错误:

Traceback (most recent call last):
File "2.py", line 23, in <module>
new_img.putdata(list(new_data))
File "2.py", line 6, in negatePixel
return tuple([255-x for x in pixel])
TypeError: 'int' object is not iterable

我编写了上面的程序来执行我想要的操作,但它出现了错误。我是编程新手,有什么办法解决这个问题吗?

最佳答案

您的方法并不理想。首先,您可以使用 ImageMagick 更简单地完成此操作,它包含在大多数 Linux 发行版中,并且适用于 macOS 和 Windows。就在终端中,这将反转当前目录中的所有文件:

magick mogrify -negate *.jpg

或者,如果您希望将它们保存在名为 results 的目录中:

mkdir results
magick mogrify -path results -negate *.jpg
<小时/>

如果你想坚持使用Python和PIL/Pillow,它的ImageOps模块中已经有一个invert()函数 here :

#!/usr/local/bin/python3

from PIL import Image, ImageOps

# Load image
im = Image.open('image.jpg')

# Invert
result = ImageOps.invert(im)

# Save
result.save('result.jpg')
<小时/>

如果您不想使用内置的 invert(),那么使用 point() 函数会更好 here :

#!/usr/local/bin/python3

from PIL import Image

# Load image
im = Image.open('image.jpg')

# Negate
result = im.point(lambda p: 255 -p)

# Save
result.save('result.jpg')

注意:一般来说,一旦您开始在 Python 中使用 for 循环或 getdata() 处理图像,您就可以可能已经出问题了。你应该使用内置库函数或 Numpy,否则一切都会变得很慢。

关于python - 使用 PIL 将多个图像转换为其负片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59964952/

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