[英]How to convert list of images into list of numbers in python? TypeError: int() argument must be a string, a bytes-like object or a number, not 'Image'
I'm writing a code to load images and resize them, after that I modified that code, splitting those resized images into three categories; 我正在编写代码以加载图像并调整图像大小,然后修改该代码,将这些调整大小后的图像分为三类: train, test and validation (according to ratios). 训练,测试和验证(根据比例)。 Then I got this error, " TypeError: int() argument must be a string, a bytes-like object or a number, not 'Image
'" after adding this line (15): img.load()
to eliminate error: ValueError: seek of closed file
. 然后,我收到以下错误消息:“ TypeError: int() argument must be a string, a bytes-like object or a number, not 'Image
'。添加此行(15): img.load()
以消除错误: ValueError: seek of closed file
。
this is code. 这是代码。
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)
this is traceback: 这是回溯:
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'
Any Solution? 有什么办法吗?
this could be one method, Keep validation set in different folder altogether. 这可能是一种方法,将验证完全设置在不同的文件夹中。 Split will happen when you will fit model (at the end of this code). 拆分将在您适合模型时发生(在此代码结尾)。 An example here. 这里有一个例子。
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
You can convert PIL images into numpy arrays. 您可以将PIL图像转换为numpy数组。 Copying an example from https://pillow.readthedocs.io/en/5.3.x/reference/Image.html#PIL.Image.fromarray - 从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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.