Created
May 8, 2023 07:48
-
-
Save tklee1975/7157d46f23e27004ec28868e7d78420d to your computer and use it in GitHub Desktop.
Python Photo Classifier (Starter Version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from keras.models import load_model # TensorFlow is required for Keras to work | |
from PIL import Image, ImageOps # Install pillow instead of PIL | |
import numpy as np | |
import os | |
import shutil | |
# ---------------------------- | |
# Setup Model | |
# ---------------------------- | |
# Disable scientific notation for clarity | |
np.set_printoptions(suppress=True) | |
# Load the model | |
model = load_model("keras_model.h5", compile=False) | |
# Load the labels | |
class_names = open("labels.txt", "r").readlines() | |
# ---------------------------- | |
# File Operations | |
# ---------------------------- | |
def list_files(directory): | |
files = [] | |
for f in os.listdir(directory): | |
if os.path.isfile(os.path.join(directory, f)): | |
files.append(f) | |
return files | |
def copy_to_class_folder(src_image, name, output_class_path): | |
if not os.path.exists(output_class_path): | |
os.makedirs(output_class_path) | |
output_file = os.path.join(output_class_path, name) | |
# copy the image to the output path | |
shutil.copy(src_image, output_file) | |
# ---------------------------- | |
# Predict Label & Score From Image | |
# ---------------------------- | |
def predict_image_label(image_path): | |
# Action: Predict the label and score from the image | |
# Hint: Use the code from photo_classifier_test.py | |
final_label = "???" | |
confidence_score = 0.0 | |
# return tuple | |
return (final_label, confidence_score) | |
# ---------------------------- | |
# Classify and Copy Image to Classified Folder | |
# ---------------------------- | |
file_counter = 0 | |
def classify_image(image_path, output_path): | |
global file_counter | |
file_counter = file_counter + 1 | |
(class_name, score) = predict_image_label(image_path) | |
print("Class:", class_name, " score: ", score, " source: ", image_path) | |
# copy the image to the output path | |
# Hint: Define out filename with class_name & filter_counter | |
# Use copy_to_class_folder to copy file | |
# ---------------------------- | |
# Main | |
# ---------------------------- | |
# Specify the directory path | |
input_path = "./input" | |
output_path = "./output" | |
files = list_files(input_path) | |
for fname in files: | |
full_name = os.path.join(input_path, fname) | |
print ("File: ", full_name) | |
classify_image(full_name, output_path) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment