[Python] Use Python's Scipy to convolve a color image with user supplied kernel

Discussão em 'Python' iniciado por Stack, Novembro 30, 2024.

  1. Stack

    Stack Membro Participativo

    I have noted that scipy.ndimage.convolve / scipy.signal.convolve (scipy.ndimage.correlate/ scipy.signal.correlate) gives unexpected (and maybe wrong results) when done on color images with user supplied kernels. However, it works fine for 2d (gray) images. Am I missing something? Kindly help. The following example illustrates this:

    import numpy as np, skimage as sk, matplotlib.pyplot as plt, imageio, PIL, scipy
    # convolving 3d input with 3d kernel directly in scipy
    input_image = np.random.randint(0, 100, (5,5,3)).astype('float32') # input image
    kernel = (np.random.randint(0, 100, (3,3,3))).astype('float32') # kernel
    kernel[..., 0] /= kernel[..., 0].sum()
    kernel[..., 1] /= kernel[..., 1].sum()
    kernel[..., 2] /= kernel[..., 2].sum()
    output = scipy.signal.convolve(input_image , kernel, 'same')
    output = np.clip(output, 0, 255).astype('uint8')

    # convolving 3d input with 3d kernel using nested loops (my ground truth)
    input_image_padded = np.pad(input_image, 1) [...,1:-1]
    s = np.zeros(input_image.shape, 'float32')
    for i in range(3):
    for x in range(input_image.shape[0]):
    for y in range(input_image.shape[1]):
    s[x,y,i] = np.sum(input_image_padded[x:x+kernel.shape[0], y:y+kernel.shape[1],i]* kernel[..., i][::-1,::-1])
    s = np.clip(s, 0, 255).astype('uint8')

    # Check results
    print(np.equal(output, s).all())
    print(output)
    print(s)

    # splitting the image and kernel into their constituent 2d images and kernels then convolving
    #them appropriately

    r1 = scipy.ndimage.convolve(input_image[..., 0], kernel[..., 0], mode =
    'constant').astype('uint8')
    r2 = scipy.ndimage.convolve(input_image[..., 1], kernel[..., 1], mode =
    'constant').astype('uint8')
    r3 = scipy.ndimage.convolve(input_image[..., 2], kernel[..., 2], mode =
    'constant').astype('uint8')
    r = np.dstack([r1,r2,r3])

    # Check results
    print(np.equal(r, s).all())
    print(r)
    print(s)

    Continue reading...

Compartilhe esta Página