Как преобразовать список изображений в список чисел в Python?Аргумент TypeError: int () должен быть строкой, байтовоподобным объектом или числом, а не 'Image' - PullRequest
0 голосов
/ 04 декабря 2018

Я пишу код для загрузки изображений и изменения их размера, после чего я изменил этот код, разделив эти изображения с измененными размерами на три категории;поезд, тестирование и валидация (согласно соотношениям).Затем я получил эту ошибку «TypeError: int() argument must be a string, a bytes-like object or a number, not 'Image» после добавления этой строки (15): img.load() для устранения ошибки: ValueError: seek of closed file.

это код.

from os import listdir
from PIL import Image as PImage
import split_folders
import os, os.path
import numpy as np
import shutil
from scipy.misc import imresize

def loadImages(path):
    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        with open(os.path.join(path, image), 'rb') as i:
            img = PImage.open(i)
            img.load()
            loadedImages.append(img)
    return loadedImages

path = "./Inputs/"
imgs = loadImages(path)

#resizing
imgs = [img.resize((160,80), PImage.ANTIALIAS) for img in imgs]
print(imgs)

# split folders
np.random.shuffle(imgs)  # now this list is shuffled
train, validate, test = np.split(imgs, [int(.7*len(imgs)), int(.85*len(imgs))])


print("loading images to Train folder")
print(train)
destination = "./Outputs/train/*.png"
# shutil.copy(np.array(train),destination)
# a = PImage.fromarray(train)
# a.save(destination,".png")
# train = PImage.fromarray(train).convert('RGB')
# train.save(destination,'PNG')


print("loading images to Test folder")
print(test)

print("loading images to Validation folder")
print(validate)

это трассировка:

Traceback (most recent call last):
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line51, in _wrapfunc
    return getattr(obj, method)(*args, **kwds)
AttributeError: 'list' object has no attribute 'swapaxes'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/thisuri/Documents/Re-Train_OCR/retrain_script.py", line 28, in <module>
    train, validate, test = np.split(imgs, [int(.7*len(imgs)), int(.85*len(imgs))])
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/lib/shape_base.py", line 785, in split
    res = array_split(ary, indices_or_sections, axis)
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/lib/shape_base.py", line 702, in array_split
    sary = _nx.swapaxes(ary, axis, 0)
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line549, in swapaxes
    return _wrapfunc(a, 'swapaxes', axis1, axis2)
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line61, in _wrapfunc
    return _wrapit(obj, method, *args, **kwds)
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/core/fromnumeric.py", line41, in _wrapit
    result = getattr(asarray(obj), method)(*args, **kwds)
  File "/home/thisuri/.local/lib/python3.6/site-packages/numpy/core/numeric.py", line 501, in asarray
    return array(a, dtype, copy=False, order=order)
TypeError: int() argument must be a string, a bytes-like object or a number, not 'Image'

Любое решение?

Ответы [ 2 ]

0 голосов
/ 04 декабря 2018

Вы можете конвертировать изображения PIL в массивы.Копирование примера из https://pillow.readthedocs.io/en/5.3.x/reference/Image.html#PIL.Image.fromarray -

from PIL import Image
import numpy as np
im = Image.open('hopper.jpg')
a = np.asarray(im)
0 голосов
/ 04 декабря 2018

это может быть один из методов. Сохраняйте валидацию в другой папке.Разделение произойдет, когда вам подойдет модель (в конце этого кода).Пример здесь.

datadir = "C:/Users..."
categories = ['A','B','C']
img_size = 200
img_size_y= 420
from tqdm import tqdm    
training_data = []

    def create_training_data():
        for category in categories:
            path = os.path.join(datadir, category)
            class_num = categories.index(category)
            for img in tqdm(os.listdir(path)):
                try:
                    img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
                    new_array = cv2.resize(img_array, (img_size,img_size_y))
                    training_data.append([new_array,class_num])
                except Exception as e:
                    pass

    create_training_data()


import random 
random.shuffle(training_data)

x = []
y = []
for features, label in training_data:
    x.append(features)
    y.append(label)

x =np.array(x).reshape(-1, img_size, img_size_y, 1)

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Activation, Flatten, Conv2D, MaxPooling2D
from tensorflow.keras.callbacks import TensorBoard
import time

dense_layers = [0,1,2]
layer_sizes = [32,64,128]
conv_layers =[1,3,5,10]

for dense_layer in dense_layers:
    for layer_size in layer_sizes:
        for conv_layer in conv_layers:
            Name= "{}-conv-{}-nodes-{}-dense-{}".format(conv_layer, layer_size,dense_layer,
                                                       int(time.time()))
            print(Name)
            tensorboard = TensorBoard(log_dir='logs/{}'.format(name)) 
            model = Sequential()

            model.add(Conv2D(layer_size, (3,3), input_shape = x.shape[1:]))
            model.add(Activation('relu'))
            model.add(MaxPooling2D(pool_size=(2,2)))

            for l in range (conv_layer-1):
                model.add(Conv2D(layer_size, (3,3)))
                model.add(Activation('relu'))
                model.add(MaxPooling2D(pool_size=(2,2)))

            model.add(Flatten())
            for l in range(dense_layer):
                model.add(Dense(layer_size))
                model.add(Activation('relu'))

            model.add(Dense(1))
            model.add(Activation('sigmoid'))
            model.compile(loss = "binary_crossentropy",
                         optimizer="adam",
                         metrics=['accuracy'])

            model.fit(x,y, batch_size=2, epochs= 10, validation_split=0.3, callbacks=[tensorboard]) 
            #here is you split happening for test  
...