为什么它在4d numpy阵列中显示不同的图像?

2024-09-28 20:48:21 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试为一堆3D图像创建一个4D阵列。我可以加载图像并正确显示图像,但在将其存储到4D阵列并显示阵列中的图像后,它显示出乱码。你知道吗

我试着比较加载的图像和从4D数组读取的图像是否相等,它打印的是真的。你知道吗

import os
from glob import glob
import numpy as np
from PIL import Image

IMG_PATH = '32x32'
img_paths = glob(os.path.join(IMG_PATH, '*.jpg'))
images = np.empty((len(img_paths), 32, 32, 3))
for i, path_i in enumerate(img_paths):
    img_i = np.array(Image.open(path_i))
    Image.fromarray(img_i, 'RGB').show() # showing correct image
    images[i] = img_i
    Image.fromarray(images[i], 'RGB').show() # showing gibberish
    print(np.array_equal(img_i, images[i])) # True
    if i == 0:
        break

我希望显示与运行images[i] = img_i完全相同的图像。你知道吗


Tags: pathfrom图像imageimportimgosnp
1条回答
网友
1楼 · 发布于 2024-09-28 20:48:21

这一行正在执行一个转换:

images[i] = img_i

因为images.dtype == np.float64,但是img_i.dtype可能np.uint8。你知道吗


您可以通过指定强制转换规则来捕捉这种类型的错误:

np.copy_to(images[i], img_i, casting='no')
# TypeError: Cannot cast scalar from dtype('uint8') to dtype('float64') according to the rule 'no'

您可以通过使用正确的类型分配数组来解决此问题:

images = np.empty((len(img_paths), 32, 32, 3), dtype=np.uint8)

或者您可以让numpy为您进行分配,但这将临时占用几乎两倍的内存:

images = np.stack([
    Image.open(path_i)
    for path_i in img_paths
], axis=0)

相关问题 更多 >