iT邦幫忙

0

python辨識影像預測問題(超出邊界)

  • 分享至 

  • xImage

IMAGEPATH = ".\images"
dirs = os.listdir(IMAGEPATH)
X=[]
Y=[]
print(dirs);
w=200 # 224
h=150 # 224
i=0
for name in dirs:
#filepaths = glob.glob(path.join(IMAGEPATH+"/"+name, '.'))
filepaths = glob.glob(path.join(IMAGEPATH,name))
filename = os.listdir(filepaths[0])
for path3 in filename :
print(path.join(filepaths[0], path3))
img = cv2.imread(path3)
img = cv2.imread(path.join(filepaths[0], path3))
if img is not None:
img = cv2.resize(img, (w,h), interpolation=cv2.INTERAREA)
imrgb = cv2.cvtColor(img, cv2.COLORBGR2RGB)
X.append(imrgb)
Y.append(i)
i=i+1
print(path3)
X = np.asarray(X)
Y = np.asarray(Y)
print(X)
print(Y)

X = X.astype('float32')
X=X/255
X=X.reshape(X.shape[0],w,h,3);

category=len(dirs)
dim=X.shape[1]
xtrain , xtest , ytrain , ytest = traintestsplit(X,Y,testsize=0.01)
print(xtrain.shape)
print(ytrain.shape)

ytrain2 = tf.keras.utils.tocategorical(ytrain, category)
ytest2 = tf.keras.utils.tocategorical(ytest, category)

print(xtrain.shape)
datagen = tf.keras.preprocessing.image.ImageDataGenerator(
rotationrange=25 ,
widthshiftrange=[-3,3],
heightshiftrange=[-3,3] ,
zoomrange=0.3 ,
dataformat='channelslast')

model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(filters=32, kernelsize=(3, 3),
padding="same",
activation='relu',
inputshape=(w,h,3)))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(50, activation='relu'))
model.add(tf.keras.layers.Dense(units=category,
activation=tf.nn.softmax ))

learningrate = 0.001
opt1 = tf.keras.optimizers.Adam(lr=learningrate)
model.compile(optimizer='adam',
loss=tf.keras.losses.SparseCategoricalCrossentropy(fromlogits=True),
metrics=['accuracy'])
model.summary()
with open("modelImageDataGeneratormyImage.json", "w") as jsonfile:
jsonfile.write(model.tojson())

checkpoint = tf.keras.callbacks.ModelCheckpoint("modelImageDataGeneratormyImage.h5", monitor='loss', verbose=1,
savebestonly=True, mode='auto', savefreq=1)

trainData=datagen.flow(xtrain,ytrain,batchsize=32)
history = model.fit(trainData,
epochs=20,
callbacks=[checkpoint]
)

score = model.evaluate(xtest, ytest, batchsize=64)

print("score:",score)

predict = model.predict(xtest)
print(xtest.shape)
print("Ans:",np.argmax(predict[0]),np.argmax(predict[1]),np.argmax(predict[2]),np.argmax(predict[3]))

predict2 = model.predictclasses(xtest)
print("predictclasses:",predict2)
print("ytest",ytest[:])
for t1 in predict2:
print(dirs[t1])***
----------------------------------------------------------------------------- print("Ans:",np.argmax(predict[0]),np.argmax(predict[1]),np.argmax(predict[2]),np.argmax(predict[3]))
IndexError: index 2 is out of bounds for axis 0 with size 2

請教各位大神
詢問一下是我哪邊超出邊界了嗎?

froce iT邦大師 1 級 ‧ 2021-02-07 23:04:58 檢舉
index是從0開始,所以你 axis 0 的 size 是2,頂多只能取0 或1吧?
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答