Code
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
# Synthetic cell: dark nucleus (0.2) inside lighter cytoplasm (0.4), on a white background
nucleus_cytoplasm = np.array([
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.2, 0.2, 0.2, 0.2, 0.4, 1.0, 1.0],
[1.0, 1.0, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0],
[1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0]
], dtype=np.float32)
S_x = np.array([
[-1, 0, +1],
[-2, 0, +2],
[-1, 0, +1]
], dtype=np.float32)
S_y = np.array([
[-1, -2, -1],
[0, 0, 0],
[+1, +2, +1]
], dtype=np.float32)
# correlate2d slides each kernel over the image without flipping it (see the note below)
G_x = signal.correlate2d(nucleus_cytoplasm, S_x, mode='same', boundary='fill', fillvalue=0.0)
G_y = signal.correlate2d(nucleus_cytoplasm, S_y, mode='same', boundary='fill', fillvalue=0.0)
G_magnitude = np.sqrt(G_x**2 + G_y**2)
fig, axes = plt.subplots(1, 4, figsize=(12, 3))
axes[0].imshow(nucleus_cytoplasm, cmap='gray', vmin=0, vmax=1)
axes[0].set_title("Original")
axes[1].imshow(G_x, cmap='RdBu_r')
axes[1].set_title("$G_x$ (vertical edges)")
axes[2].imshow(G_y, cmap='RdBu_r')
axes[2].set_title("$G_y$ (horizontal edges)")
axes[3].imshow(G_magnitude, cmap='hot')
axes[3].set_title(r"Magnitude $|\nabla I|$")
for ax in axes:
ax.axis('off')
plt.tight_layout()
plt.show()








