gpt4 book ai didi

python - matplotlib.image 和 cv2.imread 的区别

转载 作者:太空宇宙 更新时间:2023-11-03 22:22:57 25 4
gpt4 key购买 nike

当我使用 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')

最佳答案

是的,默认情况下它读取 BGR,如果你想读取灰度图像,你需要使用 imread 中的第二个参数。来自docs :

Read an image

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

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

  1. cv2.IMREAD_COLOR : Loads a color image. Any transparency of image willbe neglected. It is the default flag.
  2. cv2.IMREAD_GRAYSCALE : Loadsimage in grayscale mode
  3. cv2.IMREAD_UNCHANGED : Loads image as suchincluding alpha channel Note Instead of these three flags, you cansimply 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')

关于python - matplotlib.image 和 cv2.imread 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46947310/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com