【问题标题】:Divide a image of 512*256 into 2 images each of 256*256 using PIL使用 PIL 将 512*256 的图像分成 2 个 256*256 的图像
【发布时间】:2019-06-13 23:55:39
【问题描述】:

我有一个尺寸为 512 * 256 的图像,

左边部分应该是 NN 的输入,右边部分必须是相应的输出。因此,每张图片的尺寸为 256 * 256。

到目前为止,我做了什么来拆分两个图像:

image_dir = 'images'
image_filenames = os.listdir( image_dir )
for filename in image_filenames:
    image = Image \
        .open(os.path.join( image_dir, filename)) \
        .convert( 'RGB' )
    width , height = image.size
    x.append( np.asarray( image.crop( ( width , width/2 , width , width/2 )) ))
print( x )

输出显示一个空图像,大小为 0 * 0,

[array(<PIL.Image.Image image mode=RGB size=0x0 at 0x27049C55CF8>,
      dtype=object), array(<PIL.Image.Image image mode=RGB size=0x0 at 0x27049C55710>,
      dtype=object)]

我怎样才能完美地将 512 * 256 的图像分割成 256 * 256 的 2 个图像而不会出现上述问题使用 PIL 甚至 NumPy?

【问题讨论】:

  • 您是否有理由坚持使用 PIL 而不是仅仅使用 numpy 进行拆分?
  • 绝对不是。如果您可以在 NumPy 中提供解决方案,将会很有帮助。

标签: python image image-processing python-imaging-library


【解决方案1】:

正如您暗示的那样,您不关心解决方案是否使用 PIL,这里只涉及在命令行中使用 ImageMagick ......不需要编写任何代码:

magick image.jpg -crop 50x100% sub-%d.jpg

这给了你这两半:

sub-0.jpg
sub-1.jpg

ImageMagick 包含在大多数 Linux 发行版中,可用于 macOS 和 Windows。如果您使用的是 v6 或更早版本,请将 magick 替换为 convert。


如果您有很多事情要做,您可以使用 GNU Parallel 让它们全部并行完成,如下所示:

parallel 'magick {} -crop 50x100% {.}-sub-%d.jpg' ::: *.jpg

所以,如果你从 fred.jpg 和 bill.jpg 开始,你会得到:

-rw-r--r--   1 mark  staff      13924 13 Jun 16:52 fred-sub-0.jpg
-rw-r--r--   1 mark  staff      11650 13 Jun 16:52 fred-sub-1.jpg
-rw-r--r--   1 mark  staff      13924 13 Jun 16:52 bill-sub-0.jpg
-rw-r--r--   1 mark  staff      11650 13 Jun 16:52 bill-sub-1.jpg

【讨论】:

  • 感谢 @Mark Setchell 介绍 ImageMagick
【解决方案2】:

除非我遗漏了什么,如果你愿意使用 numpy,它应该很简单:

import numpy as np

# Create example image
A = np.random.random((512, 256, 3))

# Split the image into two images
A1 = A[:256]
A2 = A[256:]

print(A.shape)
print(A1.shape)
print(A2.shape)

这只是在第一个维度上分裂。

更通用的解决方案是:

import numpy as np

A = np.random.random((512, 256, 3))

A1 = A[:A.shape[0]//2]
A2 = A[A.shape[0]//2:]

print(A.shape)
print(A1.shape)
print(A2.shape)

在这种情况下,//2 用于整数除法。那么如果A = np.random.random((512, 256, 3) 结果将是:

(512, 256, 3)
(256, 256, 3)
(256, 256, 3)

如果A = np.random.random((513, 256, 3),结果将是:

(513, 256, 3)
(256, 256, 3)
(257, 256, 3)

如果第一个维度是奇数,您必须决定处理图像大小的差异。

【讨论】:

  • 感谢您的回答。如果它有效,我将运行它并接受答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-09-21
  • 1970-01-01
  • 2011-09-23
  • 2018-04-18
  • 1970-01-01
相关资源
最近更新 更多