matplotlib.image和cv2.imread的区别

6
当我使用matplotlib.image读取灰度图像时,它显示尺寸为(512,512),类型为float32,但是当我使用cv2.imread读取相同的图像时,它显示尺寸为(512,512,3),类型为uint8。为什么会这样?难道cv2.imread命令会自动将图像转换为BGR格式,因为默认标志吗?(我正在使用python 3和opencv2)。以下是代码:
import cv2
import matplotlib.image as mpimage
img = cv2.imread('image_1.png')
img1=mpimage.imread('image_1.png')
1个回答

7

是的,默认情况下它读取BGR格式的图像,如果您想要读取灰度图像,则需要在imread中使用第二个参数。从文档中可以了解到:

Read an image

Use the function cv2.imread() to read an image. The image should be in the working directory or a full path of image should be given.

Second argument is a flag which specifies the way image should be read.

  1. cv2.IMREAD_COLOR : Loads a color image. Any transparency of image will be neglected. It is the default flag.
  2. cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode
  3. cv2.IMREAD_UNCHANGED : Loads image as such including alpha channel Note Instead of these three flags, you can simply pass integers 1, 0 or -1 respectively.

See the code below:

import numpy as np import cv2

#Load an color image in grayscale 
img = cv2.imread('messi5.jpg',0)

因此,如果您想默认读取灰度图像,则需要在imread的第二个参数中将其设为1,而不是0。 下面您代码的这个微小更改应该可以同时读入相同的图像格式。

import cv2
import matplotlib.image as mpimage
img = cv2.imread('image_1.png', 1)
img1=mpimage.imread('image_1.png')

这是否意味着,如果我想将灰度图像转换为BGR,则无需编写单独的代码,只需使用img = cv2.imread('image_1.png')即可实现? - Hitesh
1
是的,如果您将灰度图像读入为BGR,则会有三个通道表示灰度图像的B、G和R值。 - GPPK

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接