79129069

Date: 2024-10-26 17:15:43
Score: 3.5
Natty:
Report link

I need Help.. I am working on such code, and I want to check if I am on the correct path:

Comparing two sets of input images, these inputs are slightly different from each other, let the CNN learn what is the difference and apply these differences to the new inserted unseen images later.

import os
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Reshape # Import Reshape here
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import matplotlib.pyplot as plt


train_datagen = ImageDataGenerator(rescale=1./255)
train_generator = train_datagen.flow_from_directory(
    '/content/drive/MyDrive/Train',
    target_size=(200, 200), 
    batch_size=32,
    color_mode='grayscale',  # Explicitly set color mode to grayscale
    class_mode='input') 

test_datagen = ImageDataGenerator(rescale=1./255)
test_generator = test_datagen.flow_from_directory(
    '/content/drive/MyDrive/Test',
    target_size=(200, 200),
    batch_size=32,
    color_mode='grayscale',  # Explicitly set color mode to grayscale
    class_mode='input')
model = Sequential()
model.add(Conv2D(32, (3, 3), activation='sigmoid', input_shape=(200, 200, 1)))
model.add(MaxPooling2D((2, 2)))
model.add(Conv2D(32, (3, 3), activation='relu'))
model.add(MaxPooling2D((2, 2)))
model.add(Flatten())
model.add(Dense(64, activation='relu'))
# Reshape the output to match the input image shape
model.add(Dense(200 * 200 * 1, activation='sigmoid'))
# Use tf.keras.layers.Reshape instead of just Reshape
model.add(tf.keras.layers.Reshape((200, 200, 1))) # Reshape the output to match the input image shape
model.compile(optimizer='adam', loss='mse', metrics=['mse'])
history = model.fit(
    train_generator,
    epochs=50,  # Adjust number of epochs
    validation_data=test_generator)
# steps_per_epoch and validation_steps are inferred automatically by Keras
# from the length of the generators.
import numpy as np # Import the numpy library
import matplotlib.pyplot as plt
import numpy as np

new_image_path = '/content/drive/MyDrive/Output/output/11.jpg'
# Load the image in grayscale by specifying color_mode='grayscale'
new_image = tf.keras.utils.load_img(new_image_path, target_size=(200, 200), color_mode='grayscale') 
new_image = tf.keras.utils.img_to_array(new_image)
new_image = np.expand_dims(new_image, axis=0)

predicted_image = model.predict(new_image)
# Reshape to (200, 200) by removing the extra dimension
predicted_image = predicted_image.reshape((200, 200))  

# Assuming predicted_image is still grayscale, use cmap='gray'
plt.imshow(predicted_image, cmap='gray')  
plt.show()
Reasons:
  • Blacklisted phrase (0.5): I need
  • Blacklisted phrase (2.5): I need Help
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (1):
Posted by: Ismaeil Raad Alnaab