【问题标题】:How to put each half of an image on the other half如何将图像的每一半放在另一半上
【发布时间】:2022-11-27 10:33:58
【问题描述】:

我需要用另一半替换图像的每一半:

从这个开始:

以此结尾:

我曾尝试使用裁剪,但我希望图像保持相同的尺寸,而这似乎只是将其裁剪。


im = Image.open("image.png")
w, h = im.size

im = im.crop((0,0,int(w/2),h))

im.paste(im, (int(w/2),0,w,h))

im.save('test.png')

【问题讨论】:

  • 你的问题是什么?你的代码有什么问题?请参阅How to Askquestion checklist
  • 我的问题是如何从案例 1 到案例 2(将 A 的一半放在 B 的位置,反之亦然)。我的代码不起作用,因为一半移动但图像尺寸不保持不变。我在问题中陈述了所有这些并包含图像以提供更多上下文......
  • 如果沿着中心向下的线是图像的一部分,它(或至少一半)应该在“后”图像的右边缘结束。
  • @ThePhoton 它不是它的一部分,我的错我应该把它做成虚线或指出来。虽然它可能会在以后使用。

标签: python image python-imaging-library


【解决方案1】:

如何旋转图像的x方向

你快到了。您需要将图像的左右部分保留为两个单独的变量,然后将它们以相反的方向粘贴到原始图像上。

from PIL import Image
output_image = 'test.png'
im = Image.open("input.png")
w, h = im.size
left_x = int(w / 2) - 2
right_x = w - left_x
left_portion = im.crop((0, 0, left_x, h))
right_portion = im.crop((right_x, 0, w, h))
im.paste(right_portion, (0, 0, left_x, h))
im.paste(left_portion, (right_x, 0, w, h))
im.save(output_image)
print(f"saved image {output_image}")

input.png:

output.png:

解释:

  • 我使用left_x = int(w / 2) - 2 来保持中间边界线在中间。您可以根据您的情况进行更改。

参考:

【讨论】:

    【解决方案2】:

    实际上,您可以使用 ImageChops.offset 来做到这一点:

    from PIL import Image, ImageChops
    
    # Open image
    im = Image.open('...')
    
    # Roll image by half its width in x-direction, and not at all in y-direction
    ImageChops.offset(im, xoffset=int(im.width/2), yoffset=0).save('result.png')
    

    其他库/包,例如ImageMagick, 将此操作称为“滚动”图像,因为从一个边缘滚出的像素滚入相对边缘。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-14
      • 2018-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-21
      • 1970-01-01
      相关资源
      最近更新 更多