首页 > 解决方案 > 在神经网络中改变形状、高档、图像阵列

问题描述

我有一组图像像素值,我想将其放大以输入到我的神经网络中。它是一个形状数组 (28000, 48, 48, 1)。这些是归一化的图像像素值,并且希望将它们放大到更高的分辨率以输入到我的 CNN 中。数组看起来像这样......

array([[[[-0.6098866 ],
         [-0.4592209 ],
         [-0.40325198],
         ...,
         [-0.7694696 ],
         [-0.90518403],
         [-0.95160526]],

        [[-0.66049284],
         [-0.68162924],
         [-0.694159  ],

myX_trainy_trainimage 数组的形状均为 (28000,48,48,1)。我想将这 28000 个图像阵列放大或调整大小为 75x75。请帮忙。我应该将数组转换回非标准化数组或图像,然后使用cv2进行升级吗?我该怎么做?

标签: pythoncomputer-visionconv-neural-networkobject-detectionimage-resizing

解决方案


调整图像大小的一种简单方法是使用 Python 模块 PIL(Python 图像库),您可以使用pip install pillow. 下面的示例演示调整单个图像的大小:

import numpy as np
from PIL import Image
import matplotlib.pyplot as plt

# Open image
panda_pil = Image.open("panda.jpg")
print(np.array(panda_pil).shape)
# (613, 696, 3)

panda_pil_resized = panda_pil.resize((75, 75))
print(np.array(panda_pil_resized).shape)
# (75, 75, 3)

plt.imshow(np.array(panda_pil_resized))
plt.show()

您可以按如下方式下载熊猫图像:

import urllib.request

panda_fname = "panda.jpg"
panda_url = "https://upload.wikimedia.org/wikipedia/commons/f/fe/Giant_Panda_in_Beijing_Zoo_1.JPG"
urllib.request.urlretrieve(panda_url, panda_fname)

要调整所有 28000 张图像的大小,一种方法是将其作为 for 循环中的预处理步骤,并将图像保存到 numpy 数组中。

编辑:您可以循环浏览原始的 28000x2304 图像阵列,并在for-loop 中单独升级每个图像。要从对象中获取PIL.Image对象np.ndarray,您可以使用Pil.Image.from_array,如下所示(我刚刚生成了一个随机的高斯噪声数组,但它应该与您的图像相同):

import numpy as np
from PIL import Image
from time import perf_counter

old_width, old_height = 48, 48
new_width, new_height = 75, 75
num_images = 28000

old_image_array = np.random.normal(size=[num_images, old_width*old_height])
new_image_array = np.empty(shape=[num_images, new_width*new_height])

print("Starting conversion...")
t0 = perf_counter()

# Loop over each image individually
for i in range(num_images):
    # Get the ith image and reshape
    old_image = old_image_array[i].reshape(old_width, old_height)
    # Convert to PIL.Image
    old_image_pil = Image.fromarray(old_image)
    # Upscale resolution
    new_image_pil = old_image_pil.resize((new_width, new_height))
    # Convert to numpy array
    new_image = np.array(new_image_pil)
    # Reshape and store in new image array
    new_image_array[i] = new_image.reshape(new_width*new_height)

t1 = perf_counter()
print("Time taken = {:.3f} s".format(t1 - t0))
print(old_image_array.shape, new_image_array.shape)

控制台输出:

Starting conversion...
Time taken = 2.771 s
(28000, 2304) (28000, 5625)

很可能有一种更有效的方法,但是这种方法很简单,并且使用的工具对了解它们很有用(如果您还不知道它们PIL是一个很好的图像处理模块,请参阅此博客文章如果你想了解更多关于PIL)。


推荐阅读