使用Python来反转和翻译图像 [英] Use Python to invert and translate images

查看:140
本文介绍了使用Python来反转和翻译图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了以下代码来遍历文件夹中的所有图像,创建其负片并将其保存在新的类似名称下。

I have written the following code to loop through all the images in a folder, create its negative and save it under a new similar name.

我怎样才能将它们翻译成右边5个像素?

How can I do the same thing to translate them by 5 pixels to the right?

代码:

from PIL import Image
import PIL.ImageOps
import glob

files = glob.glob('path/*.JPG') # Use *.* if you're sure all are images

for f in files:
  print(1)
  image = Image.open(f)
  inverted_image = PIL.ImageOps.invert(image)
  out = f[:f.rfind('.')]
  inverted_image.save('%s-n.JPG'%out)

我在ImageOps中搜索了一个翻译函数但找不到。还有其他办法吗?

I searched for a translate function in ImageOps but could not find one. Is there any other way?

推荐答案

您可以采取以下方法。这会创建一个大5像素的新图像,并将原始图像粘贴到新图像偏移5像素:

You could take the following approach. This creates a new image 5 pixels bigger and pastes your original image into the new image offset by 5 pixels:

from PIL import Image
import PIL.ImageOps
import glob

shift = 5
files = glob.glob('path/*.JPG') # Use *.* if you're sure all are images

for f in files:
    image = Image.open(f)
    inverted_image = PIL.ImageOps.invert(image)

    out = f[:f.rfind('.')]
    inverted_image.save('%s-n.JPG'%out)

    # Shift the image 5 pixels
    width, height = image.size
    shifted_image = Image.new("RGB", (width+shift, height))
    shifted_image.paste(image, (shift, 0))
    shifted_image.save('%s-shifted.JPG' % out)

如果你想要倒置图像移位,更改如下:

If you want the inverted images shifted, change as follows:

    shifted_image.paste(inverted_image, (shift, 0))

这篇关于使用Python来反转和翻译图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆