# Convoluting 3D image with 2D

I have a single image of shape img.shape = (500, 439, 3)

The convolution function is

def convolution(image, kernel, stride=1, pad=0):

n_h, n_w, _ = image.shape

f = kernel.shape
kernel = np.repeat(kernel[None,:], 3, axis=0)
kernel = kernel.transpose()

n_H = int(((n_h + (2*pad) - f) / stride) + 1)
n_W = int(((n_w + (2*pad) - f) / stride) + 1)
n_C = 1

out = np.zeros((n_H, n_W, n_C))

for h in range(n_H):
vert_start = h*stride
vert_end = h*stride + f

for w in range(n_W):
horiz_start = w*stride
horiz_end = w*stride + f

for c in range(n_C):
a_slice_prev = image[vert_start:vert_end,
horiz_start:horiz_end, :]

s = np.multiply(a_slice_prev, kernel)
out[h, w, c] = np.sum(s, dtype=float)

return out


The code for plotting is

img = plt.imread('cat.png')
kernel = np.arange(25).reshape((5, 5))
out2 = convolution(img, kernel)
plt.imshow(np.squeeze(out2))
plt.show()


The output seems to get a CYAN cover, is the logic of the code correct ? • The "CYAN cover" is likely because of the data type of out. ndarrays with float64 dtype, not in range [0, 1] are considered as "general data" and matplotlib falls back to its default colormap. – AlexV Feb 11 at 11:51
• @AlexV is it possible to have a colored output? – PolarBear10 Feb 11 at 13:16
• You will have to normalize your data before plotting, either to [0, 255] and using np.uint8 as dtype or [0, 1] for np.float64/np.float32. – AlexV Feb 11 at 13:29
• @AlexV I normalize it using the following out2 -= out2.min() out2 /= out2.max() and then plt.imshow(np.squeeze(out2), vmin=out2.min(), vmax=out2.max()), when I print out print('Min: %.3f, Max: %.3f' % (out2.min(), out2.max())) I get my range from 0 to 1, my datatype is still though Data Type: float64 and the image is still CYAN, Using cmap=gray gives a grey output. But still not the coloured one I am hoping for. Is it actually possible to have a coloured image with only 1 channel ? – PolarBear10 Feb 11 at 13:54
• Sorry, my bad! It's not possible to have a color image with just one channel. Grayscale is as "natural" as it gets. – AlexV Feb 11 at 14:13