这些数据是什么类型?

时间:2019-09-19 00:30:39

标签: python image-processing computer-vision data-science

请告诉我train_images的类型?它的nparray?

    data_dir = self.data_dir
    fd = open(os.path.join(data_dir, 'train-images-idx3-ubyte'))
    loaded = np.fromfile(file=fd, dtype=np.uint8)
    train_images = loaded[16:].reshape((60000, 28, 28,1)).astype(np.float)

我的另一个问题是:如何将一个文件夹的jpg图像转换为train_images格式?我想进行训练并测试数据集。 谢谢

1 个答案:

答案 0 :(得分:0)

要检查任何对象的类型,可以使用type()

print( type(train_images) ) 

许多模块(不仅用于数据科学)具有加载图像并直接创建numpy数组的功能,或者可以使用np.array()轻松地对其进行转换。

import numpy as np
import matplotlib.pyplot as plt

filename = 'image.jpg'

import matplotlib.pyplot

img = matplotlib.pyplot.imread(filename)

print(type(img), img.shape)
plt.imshow(img)
plt.show()

可能需要将BGR颜色转换为RGB

import cv2

img = cv2.imread(filename)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

print(type(img), img.shape)
plt.imshow(img)
plt.show()

import imageio

img = np.array(imageio.imread(filename))
img = np.array(img)

print(type(img), img.shape)
plt.imshow(img)
plt.show()

import PIL.Image

img = PIL.Image.open(filename)
img = np.array(img)

print(type(img), img.shape)
plt.imshow(img)
plt.show()

需要旋转-交换轴

import pygame

img = pygame.image.load(filename)
img = pygame.surfarray.array3d(img)
img = img.swapaxes(0, 1)

print(type(img), img.shape)
plt.imshow(img)
plt.show()

import skimage

img = skimage.io.imread(filename)

print(type(img), img.shape)

plt.imshow(img)
plt.show()

import scipy.misc

img = scipy.misc.imread(filename)

print('scipy:', type(img), img.shape)

plt.imshow(img)
plt.show()

它加载图像,但显示警告:

DeprecationWarning: `imread` is deprecated!
`imread` is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use ``imageio.imread`` instead.

必须将其从PIL.Image转换为numpy.array

from keras.preprocessing.image import load_img

img = load_img(filename)
img = np.array(img)

print('keras:', type(img), img.shape)

plt.imshow(img)
plt.show()