简体   繁体   English

为什么cv2.imread会更改像素值?

[英]why does cv2.imread change the pixel values?

I recently noticed that cv2.imread changes the pixel values of images. 我最近注意到cv2.imread更改了图像的像素值。 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. 我正在使用下面的代码,在这里我的输入图像是蒙版的黑白图像(在Matlab中阅读以确保像素值仅为0和1。)但是当我打印original_mask的像素值时,我看到了像素值已更改,并涉及许多不同的值。 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_image.shape时,我看到图像是RGB,这意味着具有3个通道(k,k,3)而不是1个通道!

        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. 您需要使用cv2.INTER_NEAREST作为调整大小调用的输入。 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 . 至于3个通道,它们应该都包含相同的值,因此您可以使用original_mask[...,0]分割单个通道,或者在对cv2.IMREAD_GRAYSCALE的调用中使用cv2.imread

There's a default second argument to cv2.imread() that leads to a 3-channel image. cv2.imread()有一个默认的第二个参数, cv2.imread()参数导致一个3通道图像。 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. 将导致一个单一的渠道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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