Search code examples
pythonnumpyhistogramscikit-imageopencv

skimage.io.imread Versus cv2.imread


I am using and familiar with cv2, today I was giving a try with skimage.

I was trying to read an image using skimage and cv2. It seems that they both read the image perfectly. But when I plot histograms of the image but read through different libraries (skimage and cv2), the histogram shows a significant difference.

Would anyone help me by explaining the difference between the histograms?

My code:

import cv2
import skimage.io as sk
import numpy as np
import matplotlib.pyplot as plt

path = '../../img/lenna.png'

img1 = sk.imread(path, True)
img2 = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
print(img1.shape)
print(img2.shape)

plt.subplot(2, 2, 1)
plt.imshow(img1, cmap='gray')
plt.title('skimage read')
plt.xticks([])
plt.yticks([])

plt.subplot(2, 2, 2)
plt.imshow(img2, cmap='gray')
plt.title('cv2 read')
plt.xticks([])
plt.yticks([])

plt.subplot(2, 2, 3)
h = np.histogram(img1, 100)
plt.plot(h[0])
plt.title('skimage read histogram')

plt.subplot(2, 2, 4)
h = np.histogram(img2, 100)
plt.plot(h[0])
plt.title('cv2 read histogram')

plt.show()

Text Output:

(512, 512)
(512, 512)

Output:

code output



Edit:

Here is the input image:


Solution

  • The two imread functions just have a different default format for reading the images. The skimage.io standard is using a 64-bit float, while the cv2 standard seems to be unsigned byte.
    You can see this by converting img1 to the unsigned byte format.

    import skimage as skk
    img1 = skk.img_as_ubyte(img1)
    

    Now you will get somewhat similar histograms.They are not perfectly the same because they are read initially as different formats.

    img