Fedour Traktor
Fedour Traktor

Reputation: 331

Bad display with pyplot, image too dark

I am working on an image processing problem.

I create a function that applies a salt and pepper noise to an image. Here is the function:

def sp_noise(image,prob):

    res = np.zeros(image.shape,np.uint8)
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):
            rdn = random.random()
            if rdn < prob:
                rdn2 = random.random()
                if rdn2 < 0.5:
                    res[i][j] = 0
                else:
                    res[i][j] = 255
            else:
                res[i][j] = image[i][j]
    return res

Problems happen when I want to display the result.

wood = loadPNGFile('wood.jpeg',rgb=False)
woodSP = sp_noise(bois,0.01)

plt.subplot(1,2,1)
plt.imshow(bois,'gray')
plt.title("Wood")
plt.subplot(1,2,2)
plt.imshow(woodSP,'gray')
plt.title("Wood SP")

I can not post the image directly but here is the link:

image

The picture is darker. But when I display the value of the pixels

But when I display the value of the pixels between the 2 images the values ​​are the same:

[[ 99  97  96 ... 118  90  70]
 [110 110 103 ... 116 115 101]
 [ 79  73  65 ...  96 121 121]
 ...
 [ 79  62  46 ... 105 124 113]
 [ 86  98 100 ... 114 119  99]
 [ 96  95  95 ... 116 111  90]]
[[255  97  96 ... 118  90  70]
 [110 110 103 ... 116 115 101]
 [ 79  73  65 ...  96 121 121]
 ...
 [ 79  62  46 ... 105 124 113]
 [ 86  98 100 ... 114 119  99]
 [ 96  95  95 ... 116 111  90]]

I also check the mean value:

117.79877369007804
117.81332616658703

Apparently the problem comes from the display plt.imshow, but I can not find a solution

Upvotes: 1

Views: 2364

Answers (1)

Paul92
Paul92

Reputation: 9082

Looking at the documentation of imshow, there are 2 optional parameters, vmin, vmax which:

When using scalar data and no explicit norm, vmin and vmax define the data range that the colormap covers. By default, the colormap covers the complete value range of the supplied data. vmin, vmax are ignored if the norm parameter is used.

Therefore, if no values are specified for these parameters, the range of luminosity is based on the actual data values, with the minimum value being set to black and the maximum value being set to white. This is useful in visualization, but not in comparisons, as you found out. Therefore, just set vmin and vmax to appropriate values (probably 0 and 255).

Upvotes: 1

Related Questions