I want to run a ready-trained model I found on github. This model is about image processing and scoring via images. In the introduction it says it will work if you do this: python3 main.py path/to/your/image.
This is github link: https://github.com/dominika01/pain-detection-cats
I adapted my path to this code and ran it on cmd and terminal (I've checked from 2 os for error).
Loading the image… Cropping the features… Loading model… Issue loading image
There are multiple .py files and files for more than one model in the folder. I opened main.py with spyder. ` import cv2 import numpy as np import tensorflow as tf import keypoints import joblib import sys
def preprocess_feature (feature, x_size, y_size):
resized = cv2.resize(feature, (x_size, y_size))
preprocessed = tf.keras.preprocessing.image.img_to_array(resized)
reshaped = preprocessed.reshape(1, x_size, y_size, 3)
return reshaped
def score_feature (feature, model):
probability_array = model.predict(feature)
score = np.argmax(probability_array, axis=1)
score = score[0]
confidence = round(np.max(probability_array), 2)
if confidence > 0.99:
score = 0
return score
# path to the image
print("Loading the image...")
#image_path = PATH
image_path = sys.argv[1]
`
This time too Loading the image… Cropping the features… Loading model… Issue loading image
Here sys.argv[1] causes the "IndexError: list index out of range" error. For that reason I changed it to image_path = ("/Users////.jpg"). Again: Loading the image… Cropping the features… Loading model… Issue loading image I'm stuck in the phase.
Afterwards I made a few corrections. Error: File format not supported: filepath=models-kp/model_11. Keras 3 only supports V3 .keras files and legacy H5 format files (.h5 extension). Note that the legacy SavedModel format is not supported by load_model() in Keras 3. In order to reload a TensorFlow SavedModel as an inference-only layer in Keras 3, use keras.layers.TFSMLayer(models-kp/model_11, call_endpoint=' serving_default') (note that your call_endpoint may have a different name).
I got an error like this. Afterwards, I downgraded my Keras and TF version. right now just I get the error An error occurred: No file or directory found at models-kp/model_11. Yes, there is no folder named model-kp, there is no model_1, 2 …11 in this GitHub folder. This is in keypoints.py
# global variables
INPUT_SHAPE = 256
**ITERATION = '11'**
EPOCHS = 32
BATCH_SIZE = 32
def setup_paths():
folder_dir = "data-keypoints"
folders = ['CAT_00', 'CAT_01', 'CAT_02', 'CAT_03',
'CAT_04', 'CAT_05', 'CAT_06']
return folder_dir, folders
# preprocess an individual image
def preprocess_image(img):
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) #convert to gray
img = cv2.resize(img, (INPUT_SHAPE, INPUT_SHAPE)) #resize
img = img / 255.0 #normalize pixel values
return img
# preprocess an individual set of keypoints
def preprocess_keypoints(kp, img):
kp = kp.reshape(-1, 2) #reshape the array
kp = kp * [INPUT_SHAPE / img.shape[1], INPUT_SHAPE / img.shape[0]] #resize
kp = kp / 255.0 # normalize values
return kp
# load the images and their corresponding key points
def load_data():
# set up
folder_dir, folders = setup_paths()
images = []
keypoints = []
print("Loading data…")
# iterate over the directories
for folder in folders:
path = os.path.join(folder_dir, folder, '*.jpg')
images_paths = sorted(glob.glob(path))
for image_path in images_paths:
# load image
img = cv2.imread(image_path)
# load keypoints
with open(image_path+'.cat', 'r') as f:
keypoints_text = f.read().strip()
kp = np.array(keypoints_text.split(' ')[1:], dtype=np.float32)
# Add the image and keypoints to the lists
keypoints.append(preprocess_keypoints(kp, img))
images.append(preprocess_image(img))
print("Done.\n")
return images, keypoints
# prepare the data and split the sets
def prepare_data():
# load data
images, keypoints = load_data()
# convert lists into np arrays
images = np.array(images)
keypoints = np.array(keypoints)
# reshape the arrays
images = np.expand_dims(images, axis=-1)
keypoints = keypoints.reshape(len(keypoints),18)
print("Splitting data into sets…")
# split the dataset into train and test sets
train_val_images, test_images, train_val_keypoints, test_keypoints =
model_selection.train_test_split(
images, keypoints, test_size=0.2, random_state=42)
# split the train and validation sets
train_images, val_images, train_keypoints, val_keypoints = model_selection.train_test_split(
train_val_images, train_val_keypoints, test_size=0.2, random_state=42)
print("Done.\n")
return train_images, train_keypoints, val_images, val_keypoints, test_images, test_keypoints
### BUILING & EVALUATING THE MODEL
# define the CNN architecture - might improve later
def create_model():
print("Creating the model...")
model = tf.keras.Sequential([
# convolution layers
tf.keras.layers.Conv2D(32, (3, 3), activation=tf.keras.layers.LeakyReLU(alpha=0.1),
input_shape=(INPUT_SHAPE, INPUT_SHAPE, 1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(64, (3, 3), activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(128, (3, 3), activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(256, (3, 3), activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Conv2D(512, (3, 3), activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.MaxPooling2D((2, 2)),
tf.keras.layers.Flatten(),
# dense layers
tf.keras.layers.Dense(1024, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(512, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(256, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(128, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(64, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(32, activation=tf.keras.layers.LeakyReLU(alpha=0.1)),
tf.keras.layers.Dense(18)
])
print("Done.\n")
return model
# train the model
def train_model(train_images, train_keypoints, val_images, val_keypoints):
#create the model
model = create_model()
# compile the model
print("Compiling the model...")
model.compile(optimizer='adam', loss="mean_squared_error",
metrics=['mae', RootMeanSquaredError(name='rmse'), r2, med, pck])
print("Done.\n")
# train the model
print("Training the model...")
history = model.fit(train_images, train_keypoints,
epochs=EPOCHS, batch_size=BATCH_SIZE,
validation_data=(val_images, val_keypoints))
print("Done.\n")
# save the model
**path = 'models-kp/model_' + ITERATION**
model.save(path)
return history, model
Save model path in keypoints.py. No matter what number I change the iteration number to, this time I get the error An error occurred: No file or directory found at models-kp/model_(NO).Can anyone help? This is important to me. Thanks in advance.
I want to analyze my pics with this trained model. I edit the code but its not working.