使用PIL将多幅图像转换为负片

2024-10-04 07:36:33 发布

您现在位置:Python中文网/ 问答频道 /正文

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

# 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

我写上面的程序是为了执行我想要的,但它犯了一个错误。我是编程新手,有没有办法解决这个问题


Tags: infrom图像imageimgnewfordata
1条回答
网友
1楼 · 发布于 2024-10-04 07:36:33

你的方法并不理想。首先,使用大多数Linux发行版中包含的、适用于macOS和Windows的ImageMagick可以更简单地做到这一点。仅在终端中,这将反转当前目录中的所有文件:

magick mogrify -negate *.jpg

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

mkdir results
magick mogrify -path results -negate *.jpg

如果您想继续使用Python和PIL/Pillow,那么在其ImageOps模块here中已经有一个invert()函数:

#!/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')

注意:一般来说,一旦开始使用for循环或getdata()与Python中的图像一起使用,您可能已经出错了。您应该使用内置的库函数或Numpy,否则一切都将是slo-o-o-o-o-w

相关问题 更多 >