Error in image dimensions while using edge detection model based resnets

26 Views Asked by At
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras import layers, models
from tensorflow.keras.optimizers import Adam

# Define the Residual Block
def residual_block(x, filters, kernel_size=3, stride=1):
    y = layers.Conv2D(filters, kernel_size, strides=stride, padding='same')(x)
    y = layers.BatchNormalization()(y)
    y = layers.Activation('relu')(y)

    y = layers.Conv2D(filters, kernel_size, strides=stride, padding='same')(y)
    y = layers.BatchNormalization()(y)

    # Skip connection
    if stride != 1 or x.shape[-1] != filters:
        x = layers.Conv2D(filters, kernel_size=1, strides=stride, padding='same')(x)

    out = layers.Add()([x, y])
    out = layers.Activation('relu')(out)

    return out

# Build the ResNet model for edge detection
def build_resnet_model(input_shape=(256, 256,1)):
    inputs = layers.Input(shape=input_shape)

    # Initial Convolutional Layer
    x = layers.Conv2D(64, 7, strides=2, activation='relu', padding='same')(inputs)
    x = layers.BatchNormalization()(x)

    # Residual Blocks
    x = residual_block(x, filters=64)
    x = residual_block(x, filters=64)

    x = residual_block(x, filters=128, stride=2)
    x = residual_block(x, filters=128)

    x = residual_block(x, filters=256, stride=2)
    x = residual_block(x, filters=256)

    # Output layer
    outputs = layers.Conv2D(1, 1, activation='sigmoid', padding='same')(x)

    model = models.Model(inputs=inputs, outputs=outputs, name='resnet_edge_detection')
    return model

# Load a test image
test_image_path = '/content/grayscale-image.jpg'
test_image = cv2.imread(test_image_path, cv2.IMREAD_GRAYSCALE)
test_image = np.expand_dims(test_image, axis=-1)  # Add channel dimension
test_image = cv2.resize(test_image, (256, 256))

test_image = np.expand_dims(test_image, axis=0)  # Add batch dimension

# Build the ResNet model
model = build_resnet_model()

# Load pre-trained weights if available
# model.load_weights('path/to/your/weights.h5')

# Compile the model
model.compile(optimizer=Adam(), loss='mse', metrics=['mae'])

# Make predictions on the test image
prediction = model.predict(test_image)[0, ..., 0]

# Plot the original image and the predicted edge map
plt.figure(figsize=(12, 6))

plt.subplot(1, 2, 1)
plt.imshow(test_image[0, ..., 0], cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(prediction, cmap='gray')
plt.title('Predicted Edge Map')

plt.show()

type here

When I run the above code, an issue appeared whicle I am using an image match the dimention of the model inputs

ValueError                                Traceback (most recent call last)
<ipython-input-19-f1e611b087b1> in <cell line: 59>()
     57 
     58 # Build the ResNet model
---> 59 model = build_resnet_model()
     60 
     61 # Load pre-trained weights if available

3 frames
/usr/local/lib/python3.10/dist-packages/keras/src/layers/merging/base_merge.py in _compute_elemwise_op_output_shape(self, shape1, shape2)
     72             else:
     73                 if i != j:
---> 74                     raise ValueError(
     75                         "Inputs have incompatible shapes. "
     76                         f"Received shapes {shape1} and {shape2}"

ValueError: Inputs have incompatible shapes. Received shapes (64, 64, 128) and (32, 32, 128)
0

There are 0 best solutions below