裁剪 numpy.ndArray 会抛出 - ValueError: 无法将空图像写入 JPEG

问题描述 投票:0回答:1

我正在尝试将 numpy 数组图像裁剪成较小的图块并保存它们:但是当我尝试保存图块时,我收到图像为空的错误。

我的脚本考虑了未达到图块大小的多余像素并将其扩展到边界。

print("Slicing Image.")

path = 'Sliced/'
filename= 'sample_svs_2_'
img = tif.imread('sample_svs_2.svs')
print(type(img)) 
print(img.shape) 

#This works, proving that 
#this method of saving is valid
data = im.fromarray(img)
data.save('Sliced/sample.jpg') 


#depth, height, width  = img.shape
height, width, depth = img.shape
tilesize = 256

print("Height: ", height)
print("Width: ", width)
print("Depth: ", depth)

leftExcessPixels = int((width%tilesize)/2)
topExcessPixels = int((height%tilesize)/2)
XNumberOfTiles = int(width/tilesize)
YNumberOfTiles = int(height/tilesize)

print('Left Excess Pixels: ' + str(leftExcessPixels) )
print('Top Excess Pixels: ' + str(topExcessPixels) )

print('Number of X tiles: ' + str(XNumberOfTiles))
print('Number of Y tiles: ' + str(YNumberOfTiles))

for y in range(YNumberOfTiles):
    for x in range(XNumberOfTiles):
        XStart = (leftExcessPixels + (tilesize * x))
        YStart = (topExcessPixels + (tilesize * y))
        XEnd = XStart + tilesize
        YEnd = YStart + tilesize
        croppedImage = img[XStart:YStart, XEnd:YEnd] 
        data = im.fromarray(croppedImage)
        data.save('Sliced/sample_x' + str(x) + '_y' + str(y) + '.jpg') 

终端输出:

Slicing Image.
<class 'numpy.ndarray'>
(13271, 19992, 3)
Height:  13271
Width:  19992
Depth:  3
Left Excess Pixels: 12
Top Excess Pixels: 107
Number of X tiles: 78
Number of Y tiles: 51
Traceback (most recent call last):
  File "c:\fileImageSlicer.py", line 72, in <module>
    sliceImage()
  File "c:\fileImageSlicer.py", line 52, in sliceImage
    data.save('Sliced/sample_x' + str(x) + '_y' + str(y) + '.jpg')
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\miniconda3\Lib\site-packages\PIL\Image.py", line 2439, in save
    save_handler(self, fp, filename)
  File "C:\miniconda3\Lib\site-packages\PIL\JpegImagePlugin.py", line 647, in _save
    raise ValueError(msg)
ValueError: cannot write empty image as JPEG

我可能做错了什么?我完全忽略的一件事是正在读取的图像有一个 z 维度(深度?)我不确定为什么图像有深度(可能是颜色?RGB),而且我不知道如何使用它..

python numpy numpy-ndarray
1个回答
0
投票

错误所在:

croppedImage = img[XStart:YStart, XEnd:YEnd]

数组切片的正确方式应该是:

croppedImage = img[YStart:YEnd, XStart:XEnd]

这样每个裁剪后的图像都有形状

(256, 256, 3)

© www.soinside.com 2019 - 2024. All rights reserved.