matplotlibimage-processingrgbnumpy-slicingbgr

Slicing the channels of image and storing the channels into numpy array(same size as image). Plotting the numpy array not giving the original image


I separated the 3 channels of an colour image. I created a new NumPy array of the same size as the image, and stored the 3 channels of the image into 3 slices of the 3D NumPy array. After plotting the NumPy array, the plotted image is not same as original image. Why is this happening?

Both img and new_img array have same elements, but image is different.

    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt
    import numpy as np

    img=mpimg.imread('/storage/emulated/0/1sumint/kali5.jpg')

    new_img=np.empty(img.shape)

    new_img[:,:,0]=img[:,:,0]
    new_img[:,:,1]=img[:,:,1]
    new_img[:,:,2]=img[:,:,2]

    plt.imshow(new_img)
    plt.show()

Expect the same image as original image.


Solution

  • The problem is that your new image will be created with the default data type of float64 on this line:

    new_img=np.empty(img.shape)
    

    unless you specify a different dtype.

    You can either (best) copy the original image's dtype like this:

    new_img = np.empty(im.shape, dtype=img.dtype)
    

    or use something like this:

    new_img = np.zeros_like(im) 
    

    or (worst) specify one you happen to know matches your data, like this,

    new_img = np.empty(im.shape, dtype=np.uint8)
    

    I presume you have some reason for copying one channel at a time, but if not, you can avoid all the foregoing issues and just do:

    new_img = np.copy(img)