使用PIL将512 * 256的图像分为256 * 256的2个图像

时间:2019-06-13 12:51:59

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

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

enter image description here

左部分应该是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图像完美地分成2个256 * 256图像,而不会出现上述使用PIL甚至NumPy 的问题?

2 个答案:

答案 0 :(得分:2)

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

public class LoginController : ApiController
{
    [HttpPost]
    [Route("api/Login")]
    public void Authenticate()
    {
        // authenticate here
    }

    [HttpPost]
    public void Register()
    {
        // register here
    }
}

这给了你两半:

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

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


如果您有很多工作要做,可以使用 GNU Parallel 并行完成所有操作,如下所示:

convert

因此,如果您以parallel 'magick {} -crop 50x100% {.}-sub-%d.jpg' ::: *.jpg fred.jpg开头,则会得到以下信息:

bill.jpg

答案 1 :(得分:1)

除非我缺少任何内容,并且如果您愿意使用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)

如果第一维的数字为奇数,则必须决定处理图像大小的差异。