Commit 108c8743 authored by Shahjhan  Alam's avatar Shahjhan Alam
Browse files

03062024

No related merge requests found
# import os
# import tensorflow as tf
# from tensorflow.keras.preprocessing.image import img_to_array, load_img
# import matplotlib.pyplot as plt
# # function to get the label based on prediction
# def get_label(prediction):
# return "Positive" if prediction == 1 else "Negative"
# # Load the frozen graph
# frozen_graph_path = "/demo/model_record/frozen_graph.pb"
# def load_frozen_graph(frozen_graph_filename):
# with tf.io.gfile.GFile(frozen_graph_filename, "rb") as f:
# graph_def = tf.compat.v1.GraphDef()
# graph_def.ParseFromString(f.read())
# return graph_def
# print('Loading frozen graph...', end='')
# graph_def = load_frozen_graph(frozen_graph_path)
# print('Done!')
# # Define the function to load and preprocess the image
# def load_and_preprocess_image(image_path, target_size=(120, 120)):
# # Load the image from the given path and resize it
# image = load_img(image_path, target_size=target_size)
# # Convert the image to a NumPy array
# image = img_to_array(image)
# image = image / 255.0
# # Expand dimensions to match the input shape expected by the model
# image = tf.expand_dims(image, axis=0)
# return image
# # Create a session and import the graph
# def create_session(graph_def):
# graph = tf.Graph()
# with graph.as_default():
# tf.import_graph_def(graph_def, name="")
# return tf.compat.v1.Session(graph=graph)
# session = create_session(graph_def)
# # Directory paths for input and output images
# input_dir = 'input' # Assuming input images are inside the 'input' directory
# output_dir = 'output' # Output directory
# # Create output directory if it doesn't exist
# os.makedirs(output_dir, exist_ok=True)
# # Input and output tensor names (adjust as necessary)
# input_tensor_name = 'input_tensor_name:0'
# output_tensor_name = 'output_tensor_name:0'
# # Process each image in the input directory
# for filename in os.listdir(input_dir):
# if filename.endswith(('.jpg', '.png', '.jpeg')):
# # Load and preprocess the image
# image_path = os.path.join(input_dir, filename)
# image = load_and_preprocess_image(image_path)
# # Perform inference
# predictions = session.run(output_tensor_name, feed_dict={input_tensor_name: image})
# binary_prediction = 1 if predictions[0] < 0.5 else 0
# label = get_label(binary_prediction)
# # Copy the image to the output directory with the predicted label
# output_filename = f"predicted_{filename}"
# output_path = os.path.join(output_dir, output_filename)
# plt.figure(figsize=(6, 6))
# plt.imshow(load_img(image_path))
# plt.title(f"Predicted Label: {label}")
# plt.axis('off')
# plt.savefig(output_path) # Save the figure as the output image
# plt.close() # Close the figure to release memory
# # Close the session
# session.close()
# import os
# import tensorflow as tf
# from tensorflow.keras.preprocessing.image import img_to_array, load_img
# import matplotlib.pyplot as plt
# # function to get the label based on prediction
# def get_label(prediction):
# return "Positive" if prediction == 1 else "Negative"
# # Directory paths for input and output images
# input_dir = 'input' # Assuming input images are inside the 'input' directory
# output_dir = 'output' # Output directory
# # Create output directory if it doesn't exist
# os.makedirs(output_dir, exist_ok=True)
# # Load the saved model
# model_path = "/model/model_record/saved_model"
# print('Loading model...', end='')
# model = tf.saved_model.load(model_path)
# print('Done!')
# # Define the function to preprocess the image
# def preprocess_image(image_path, target_size=(120, 120)):
# # Load the image from the given path and resize it
# image = load_img(image_path, target_size=target_size)
# # Convert the image to a NumPy array
# image = img_to_array(image)
# image = image / 255.0
# # Expand dimensions to match the input shape expected by the model
# image = tf.expand_dims(image, axis=0)
# return image
# # Process each image in the input directory
# for filename in os.listdir(input_dir):
# if filename.endswith(('.jpg', '.png', '.jpeg')):
# # Load and preprocess the image
# image_path = os.path.join(input_dir, filename)
# image = preprocess_image(image_path)
# # Perform inference
# predictions = model(image)
# binary_prediction = 1 if predictions[0] < 0.5 else 0
# label = get_label(binary_prediction)
# # Copy the image to the output directory with the predicted label
# output_filename = f"predicted_{filename}"
# output_path = os.path.join(output_dir, output_filename)
# plt.figure(figsize=(6, 6))
# plt.imshow(load_img(image_path))
# plt.title(f"Predicted Label: {label}")
# plt.axis('off')
# plt.savefig(output_path) # Save the figure as the output image
# plt.close() # Close the figure to release memory
# import os
# import tensorflow as tf
# from tensorflow.keras.preprocessing.image import img_to_array, load_img
# import matplotlib.pyplot as plt
# # Function to get the label based on prediction
# def get_label(prediction):
# return "Positive" if prediction == 1 else "Negative"
# # Print the current working directory
# print(f"Current working directory: {os.getcwd()}")
# # Directory paths for input and output images
# input_dir = 'input' # Assuming input images are inside the 'input' directory
# output_dir = 'output' # Output directory
# # Create output directory if it doesn't exist
# if not os.path.exists(output_dir):
# os.makedirs(output_dir)
# print(f"Created output directory: {output_dir}")
# else:
# print(f"Output directory already exists: {output_dir}")
# # Print absolute path of the output directory
# print(f"Absolute path of the output directory: {os.path.abspath(output_dir)}")
# # Load the saved model
# model_path = "/model/model_record/saved_model"
# print('Loading model...', end='')
# try:
# model = tf.saved_model.load(model_path)
# infer = model.signatures["serving_default"]
# print('Done!')
# except Exception as e:
# print(f'Error loading model: {e}')
# raise
# # Define the function to preprocess the image
# def preprocess_image(image_path, target_size=(120, 120)):
# # Load the image from the given path and resize it
# image = load_img(image_path, target_size=target_size)
# # Convert the image to a NumPy array
# image = img_to_array(image)
# image = image / 255.0
# # Expand dimensions to match the input shape expected by the model
# image = tf.expand_dims(image, axis=0)
# return image
# # Process each image in the input directory
# for filename in os.listdir(input_dir):
# if filename.endswith(('.jpg', '.png', '.jpeg')):
# try:
# # Load and preprocess the image
# image_path = os.path.join(input_dir, filename)
# print(f'Processing image: {image_path}')
# image = preprocess_image(image_path)
# # Perform inference
# predictions = infer(tf.constant(image))
# predicted_value = predictions["dense_1"].numpy()[0][0] # Adjust this key based on your model's output signature
# binary_prediction = 1 if predicted_value < 0.5 else 0
# label = get_label(binary_prediction)
# # Copy the image to the output directory with the predicted label
# output_filename = f"predicted_{filename}"
# output_path = os.path.join(output_dir, output_filename)
# plt.figure(figsize=(6, 6))
# plt.imshow(load_img(image_path))
# plt.title(f"Predicted Label: {label}")
# plt.axis('off')
# plt.savefig(output_path) # Save the figure as the output image
# plt.close() # Close the figure to release memory
# print(f'Saved predicted image to: {output_path}')
# # Verify the file was created
# if os.path.exists(output_path):
# print(f"File exists: {output_path}")
# else:
# print(f"File does not exist: {output_path}")
# except Exception as e:
# print(f'Error processing {filename}: {e}')
import os
import tensorflow as tf
from tensorflow.keras.preprocessing.image import img_to_array, load_img
import matplotlib.pyplot as plt
# function to get the label based on prediction
# Function to get the label based on prediction
def get_label(prediction):
return "Positive" if prediction == 1 else "Negative"
# Load the frozen graph
frozen_graph_path = "/demo/model_record/frozen_graph.pb"
# Print the current working directory
print(f"Current working directory: {os.getcwd()}")
# Directory paths for input and output images
input_dir = 'input' # Assuming input images are inside the 'input' directory
model_record_dir = 'model_record' # The model record directory
output_dir = os.path.join(model_record_dir, 'output') # Output directory inside the model record directory
# Resolve absolute paths
input_dir = os.path.abspath(input_dir)
model_record_dir = os.path.abspath(model_record_dir)
output_dir = os.path.abspath(output_dir)
# Print resolved paths for input and output directories
print(f"Absolute path of the input directory: {input_dir}")
print(f"Absolute path of the model record directory: {model_record_dir}")
print(f"Absolute path of the output directory: {output_dir}")
def load_frozen_graph(frozen_graph_filename):
with tf.io.gfile.GFile(frozen_graph_filename, "rb") as f:
graph_def = tf.compat.v1.GraphDef()
graph_def.ParseFromString(f.read())
return graph_def
# Create model record directory if it doesn't exist
if not os.path.exists(model_record_dir):
os.makedirs(model_record_dir)
print(f"Created model record directory: {model_record_dir}")
else:
print(f"Model record directory already exists: {model_record_dir}")
# Create output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)
print(f"Created output directory: {output_dir}")
else:
print(f"Output directory already exists: {output_dir}")
print('Loading frozen graph...', end='')
graph_def = load_frozen_graph(frozen_graph_path)
print('Done!')
# Load the saved model
model_path = os.path.join(model_record_dir, 'saved_model')
print(f"Absolute path of the model: {model_path}")
# Define the function to load and preprocess the image
def load_and_preprocess_image(image_path, target_size=(120, 120)):
print('Loading model...', end='')
try:
model = tf.saved_model.load(model_path)
infer = model.signatures["serving_default"]
print('Done!')
except Exception as e:
print(f'Error loading model: {e}')
raise
# Define the function to preprocess the image
def preprocess_image(image_path, target_size=(120, 120)):
# Load the image from the given path and resize it
image = load_img(image_path, target_size=target_size)
# Convert the image to a NumPy array
......@@ -31,47 +294,37 @@ def load_and_preprocess_image(image_path, target_size=(120, 120)):
image = tf.expand_dims(image, axis=0)
return image
# Create a session and import the graph
def create_session(graph_def):
graph = tf.Graph()
with graph.as_default():
tf.import_graph_def(graph_def, name="")
return tf.compat.v1.Session(graph=graph)
session = create_session(graph_def)
# Process each image in the input directory
for filename in os.listdir(input_dir):
if filename.endswith(('.jpg', '.png', '.jpeg')):
try:
# Load and preprocess the image
image_path = os.path.join(input_dir, filename)
print(f'Processing image: {image_path}')
image = preprocess_image(image_path)
# Directory paths for input and output images
input_dir = 'input' # Assuming input images are inside the 'input' directory
output_dir = 'output' # Output directory
# Perform inference
predictions = infer(tf.constant(image))
predicted_value = predictions["dense_1"].numpy()[0][0] # Adjust this key based on your model's output signature
binary_prediction = 1 if predicted_value < 0.5 else 0
label = get_label(binary_prediction)
# Create output directory if it doesn't exist
os.makedirs(output_dir, exist_ok=True)
# Copy the image to the output directory with the predicted label
output_filename = f"predicted_{filename}"
output_path = os.path.join(output_dir, output_filename)
plt.figure(figsize=(6, 6))
plt.imshow(load_img(image_path))
plt.title(f"Predicted Label: {label}")
plt.axis('off')
plt.savefig(output_path) # Save the figure as the output image
plt.close() # Close the figure to release memory
print(f'Saved predicted image to: {output_path}')
# Input and output tensor names (adjust as necessary)
input_tensor_name = 'input_tensor_name:0'
output_tensor_name = 'output_tensor_name:0'
# Verify the file was created
if os.path.exists(output_path):
print(f"File exists: {output_path}")
else:
print(f"File does not exist: {output_path}")
# Process each image in the input directory
for filename in os.listdir(input_dir):
if filename.endswith(('.jpg', '.png', '.jpeg')):
# Load and preprocess the image
image_path = os.path.join(input_dir, filename)
image = load_and_preprocess_image(image_path)
# Perform inference
predictions = session.run(output_tensor_name, feed_dict={input_tensor_name: image})
binary_prediction = 1 if predictions[0] < 0.5 else 0
label = get_label(binary_prediction)
# Copy the image to the output directory with the predicted label
output_filename = f"predicted_{filename}"
output_path = os.path.join(output_dir, output_filename)
plt.figure(figsize=(6, 6))
plt.imshow(load_img(image_path))
plt.title(f"Predicted Label: {label}")
plt.axis('off')
plt.savefig(output_path) # Save the figure as the output image
plt.close() # Close the figure to release memory
# Close the session
session.close()
except Exception as e:
print(f'Error processing {filename}: {e}')
output/predicted_001-85.jpg

34.8 KB

output/predicted_001-86.jpg

37.9 KB

output/predicted_001-87.jpg

34 KB

output/predicted_001-88.jpg

32.7 KB

output/predicted_001-89.jpg

31.1 KB

output/predicted_003-114.jpg

41.3 KB

output/predicted_003-132.jpg

41.6 KB

output/predicted_003-150.jpg

40.8 KB

output/predicted_003-168.jpg

39.8 KB

output/predicted_003-96.jpg

40.2 KB

output/predicted_003-97.jpg

41.7 KB

Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment