why does cv2.imread change the pixel values?

10 views
Skip to first unread message

Goli

unread,
Dec 11, 2018, 12:29:01 AM12/11/18
to OpenCV with Python Blueprints
I recently noticed that cv2.imread changes the pixel values of images. I am doing segmentation so pixel values are important as different pixel values show different labels. I am using the code below and here my input images are masked black and white images (pixel values are only 0 and 1 as I read them in matlab to make sure.) but when I print pixel values of original_mask I see that the pixel values has been changed and goes over many different values. Any help is greatly appreciated.
Moreover, when I print original_image.shape I see that the image is RGB which means has 3 channels (k, k, 3) and not 1 channel!!!!


original_mask = cv2.imread(mask_dir + '/'+lists.iloc[i, 0] + '.png')
        print(original_mask, "original_masklllll")
        print(original_mask.shape, "original_mask")
        resized_mask = cv2.resize(original_mask, (256, 256))
        print(resized_mask.shape, "resized_mask")
        print(resized_mask, "resized_mask")
        print(resized_mask[:, :, 0], "resized_mask[:, :, 0]")


Michael Beyeler

unread,
Dec 11, 2018, 12:22:58 PM12/11/18
to OpenCV with Python Blueprints
Hi,

You didn't post the output of these calls, so it's hard to know what went wrong with this exact image.

But, png images usually come with 3 channels (or 4, since they can also have an alpha channel). You can load them as grayscale via:

original_mask = cv2.imread(imgfile, cv2.IMREAD_GRAYSCALE)

If you want a binary mask (assumes original_mask has values in [0, 255]):

thresh, binary_mask = cv2.threshold(original_mask, 127, 255, cv2.THRESH_BINARY)

All very cumbersome. An alternative is to use scikit-image:

import numpy as np
import skimage.io as skio
binary_mask
= skio.imread(imgfile, dtype=np.uint8)

You can also store them as dtype=np.bool, in which case all "pixel values" are True/False.

A sidenote is that cv2.resize does not change the number of channels. If you're image has size (n, n, 3) and you resize by specifying (k, k), then the resulting image will be (k, k, 3), not (k, k, 1).


Cheers,
Michael
Reply all
Reply to author
Forward
0 new messages