简体   繁体   中英

why does cv2.imread change the pixel values?

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]")

You need to use cv2.INTER_NEAREST as input to the resize call. Otherwise you will be interpolating the vales between pixels, which is not the desired behavior. More info here .

cv2.resize(original_mask, (256,256),interpolation=cv2.INTER_NEAREST)

As for the 3 channels they should all contain the same value, so you can slice off a single channel with original_mask[...,0] , or use cv2.IMREAD_GRAYSCALE in the call to cv2.imread .

There's a default second argument to cv2.imread() that leads to a 3-channel image. In the case of a single-channel source image, passing

img = cv2.imread(path, cv2.IMREAD_UNCHANGED)

or, in the the case of an arbitrary image, passing

img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)

will result in a single channel.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM