I am not able to display correct prediction of an array containing 4 folder of images
from PIL import Image
import cv2
import time
def load_and_preprocess_image(img_path, target_size=(112,112)):
try:
img = Image.open(img_path)
img = img.resize(target_size)
img_array = np.array(img)
img_array = img_array / 255.0 # Normalize to [0, 1] range
return img_array
except Exception as e:
print(f"Error loading image {img_path}: {e}")
return None
def load_images_from_folders(folders, target_size):
images = []
folder_images = []
for folder in folders:
if not os.listdir(folder):
raise ValueError(f"Folder {folder} is empty.")
for img_name in os.listdir(folder):
img_path = os.path.join(folder, img_name)
if img_name.lower().endswith(( '.jpg', )):
img_array = load_and_preprocess_image(img_path, target_size)
if img_array is not None:
folder_images.append(img_array)
images.append(np.concatenate(folder_images, axis=0))
return images
def main(Model_Enhancer, folders, target_size=(112, 112)):
images = load_images_from_folders(folders, target_size)
num_images = min(len(images[0]), len(images[1]), len(images[2]), len(images[3]))
Input_Sample1 = tf.keras.Input(shape=(112, 112, 3), name='Input_Sample1')
Input_Sample2 = tf.keras.Input(shape=(112, 112, 3), name='Input_Sample2')
Input_Sample3 = tf.keras.Input(shape=(112, 112, 3), name='Input_Sample3')
Input_Sample4 = tf.keras.Input(shape=(112, 112, 3), name='Input_Sample4')
Input_Sample1 = np.concatenate(images[0][:num_images], axis=0)
Input_Sample1 = Input_Sample1.reshape((-1, 112, 112, 3))
Input_Sample2 = np.concatenate(images[1][:num_images], axis=0)
Input_Sample2 = Input_Sample2.reshape((-1, 112, 112, 3))
Input_Sample3 = np.concatenate(images[2][:num_images], axis=0)
Input_Sample3 = Input_Sample3.reshape((-1, 112, 112, 3))
Input_Sample4 = np.concatenate(images[2][:num_images], axis=0)
Input_Sample4 = Input_Sample4.reshape((-1, 112, 112, 3))
predictions = Model_Enhancer.predict([Input_Sample1,Input_Sample2,Input_Sample3,Input_Sample4])
for i, prediction in enumerate(predictions):
output_file = os.path.join('/content/drive/MyDrive/Dataset', f'output_{[i]}.jpg')
normalized_prediction = (prediction - prediction.min()) / (prediction.max() - prediction.min())
plt.imshow(normalized_prediction)
plt.title(f"Prediction: {np.argmax(prediction)}")
plt.axis('off')
plt.show()
prediction_img = Image.fromarray((normalized_prediction * 255).astype(np.uint8))
prediction_img.save(output_file)
print(f'Output image saved as {output_file}')
if name == “main“:
input_shape = (112, 112, 3)
Output =merge(Input_Sample1,Input_Sample2,Input_Sample3,Input_Sample4)
Model_Enhancer = tf.keras.Model(inputs=[Input_Sample1,Input_Sample2,Input_Sample3,Input_Sample4], outputs=Output)
folders = [
"/content/drive/MyDrive/Dataset/input_wb_train",
"/content/drive/MyDrive/Dataset/input_gc_train",
"/content/drive/MyDrive/Dataset/input_ce_train",
"/content/drive/MyDrive/Dataset/input_train"
] # Change these to your image folder paths
main(Model_Enhancer, folders,target_size=(112, 112))
Help me with this code or give me the correct to get correct prediction of images
I was expecting a correcting prediction of images, though, images are displayed still those are not the desired images
Enhanced output image
Here it is showing
KeyError Traceback (most recent call last)
/usr/local/lib/python3.10/dist-packages/PIL/Image.py in fromarray(obj, mode)
3079 try:
-> 3080 mode, rawmode = _fromarray_typemap[typekey]
3081 except KeyError as e:
KeyError: ((1, 1, 112, 3), ‘|u1’)
The above exception was the direct cause of the following exception:
TypeError Traceback (most recent call last)
2 frames
/usr/local/lib/python3.10/dist-packages/PIL/Image.py in fromarray(obj, mode)
3081 except KeyError as e:
3082 msg = “Cannot handle this data type: %s, %s” % typekey
-> 3083 raise TypeError(msg) from e
3084 else:
3085 rawmode = mode
TypeError: Cannot handle this data type: (1, 1, 112, 3), |u1
Bhargav Sai Ved Rapolu is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.