Spaces:
Running
Running
import os | |
os.environ["TF_ENABLE_ONEDNN_OPTS"] = "0" | |
os.environ["KERAS_BACKEND"] = "jax" | |
import cv2 | |
import numpy as np | |
from PIL import Image | |
import matplotlib.pyplot as plt | |
import keras | |
def resize_for_inference(input_image_path): | |
# Load the input image | |
image = cv2.imread(input_image_path) | |
# Convert the image to RGB format (for compatibility with GrabCut) | |
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
# Initialize the mask for GrabCut | |
mask = np.zeros(image.shape[:2], np.uint8) | |
# Define the rectangle for the GrabCut algorithm | |
height, width = image.shape[:2] | |
rect = (10, 10, width - 20, height - 20) # Slightly smaller than the full image | |
# Allocate memory for the GrabCut algorithm | |
bgd_model = np.zeros((1, 65), np.float64) | |
fgd_model = np.zeros((1, 65), np.float64) | |
# Apply the GrabCut algorithm | |
cv2.grabCut(image_rgb, mask, rect, bgd_model, fgd_model, 5, cv2.GC_INIT_WITH_RECT) | |
# Convert the mask to binary (foreground is white, background is black) | |
binary_mask = np.where((mask == 2) | (mask == 0), 0, 255).astype('uint8') | |
# Resize the binary mask to the desired shape (960x720) | |
resized_mask = cv2.resize(binary_mask, (720, 960), interpolation=cv2.INTER_AREA) | |
# Further resize the mask to target size (224x224) | |
target_size = (224, 224) | |
final_resized_mask = cv2.resize(resized_mask, target_size, interpolation=cv2.INTER_AREA) | |
final_resized_mask = np.expand_dims(final_resized_mask, axis=-1) | |
# Save the resized binary mask | |
return final_resized_mask | |
# Call the function with the input image path | |
resized_image=resize_for_inference("download.jpg") | |
resized_image.shape | |
loaded_model = keras.saving.load_model("hf://datasciencesage/bodym_measurement_model") | |
single_image_expanded = np.expand_dims(resized_image, axis=0) | |
predicted_vales=loaded_model.predict(single_image_expanded)[0] | |
columns = ['ankle', 'arm-length', 'bicep', 'calf', 'chest', | |
'forearm', 'height', 'hip', 'leg-length', 'shoulder-breadth', | |
'shoulder-to-crotch', 'thigh', 'waist', 'wrist'] | |
for body_type,measurement in zip(columns,predicted_vales): | |
print(body_type ," is ",measurement) |