Skip to content

Instantly share code, notes, and snippets.

@algonacci
Last active October 28, 2023 05:59
Show Gist options
  • Save algonacci/e0ad342430e43d9a0936ff7d7b4be7fa to your computer and use it in GitHub Desktop.
Save algonacci/e0ad342430e43d9a0936ff7d7b4be7fa to your computer and use it in GitHub Desktop.
Model predicting image in bulking
import os
from keras.models import load_model
from PIL import Image, ImageOps
import numpy as np
# Load the model
model = load_model("keras_Model.h5", compile=False)
# Load the labels
class_names = open("labels.txt", "r").readlines()
# Define the image folder
image_folder = "/Users/ericjulianto/Downloads/FINAL_DATASET_BARANG/test/Asli"
# Loop through all images in the folder and make predictions
for filename in os.listdir(image_folder):
if filename.endswith(".jpg") or filename.endswith(".png"): # Filter only image files
# Read the image
image_path = os.path.join(image_folder, filename)
image = Image.open(image_path).convert("RGB")
# Resize and normalize the image
size = (224, 224)
image = ImageOps.fit(image, size, Image.Resampling.LANCZOS)
image_array = np.asarray(image)
normalized_image_array = (image_array.astype(np.float32) / 127.5) - 1
# Load the image into the array
data = np.ndarray(shape=(1, 224, 224, 3), dtype=np.float32)
data[0] = normalized_image_array
# Predict with the model
prediction = model.predict(data)
index = np.argmax(prediction)
class_name = class_names[index]
confidence_score = prediction[0][index]
# Print the prediction result
print("File:", filename)
print("Class:", class_name)
print("Confidence Score:", confidence_score)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment