0
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)
4
  • You got the "Inputs have incompatible shapes. Received shapes (64, 64, 128) and (32, 32, 128)" error message. The computer has difficulty to use the (64, 64, 128) and the (32, 32, 128) dimension tensor. It means that some of the residual_block receives an invalid shape. To debug this, print out the layers' output shape. After that, you will know where the shape went wrong. Commented Dec 12, 2023 at 16:30
  • @PéterSzilvási Thank you for your reply, I solved it by applying: y = layers.Conv2D(filters, kernel_size, strides=1, padding='same')(y) in the second Conv2D of the resnet block Commented Dec 13, 2023 at 18:41
  • Wait a minute! Why does it work in the y = layers.Conv2D(filters, kernel_size, strides=1, padding='same')(y) case and why does it not work in the y = layers.Conv2D(filters, kernel_size, strides=stride, padding='same')(y) case? If the stride default value is 1. Thus, the two statement is equivalent. Commented Dec 14, 2023 at 13:43
  • @PéterSzilvási To be honest, I thought as you were I found there's no difference there, but still works. In programming, if there is something is running with no issue then just let it run 😁 Commented Dec 15, 2023 at 15:09

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.