简体   繁体   English

matplotlib.image和cv2.imread之间的区别

[英]Difference between matplotlib.image and cv2.imread

When i read a grayscale image with matplotlib.image it shows dimension (512,512) and type (float32) but when i use cv2.imread for the same image it shows (512,512,3) and type uint8. 当我使用matplotlib.image读取灰度图像时,它显示尺寸(512,512)和类型(float32),但是当我对同一图像使用cv2.imread时,它显示(512,512,3)并键入uint8。 Why is it so? 为什么会这样呢? Is cv2.imread command automatically converted image to BGR format, because of default flag. cv2.imread命令是否由于默认标志而自动将图像转换为BGR格式。 ( I am using python 3 and opencv2.) Following is code: (我正在使用python 3和opencv2。)以下是代码:

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

Yes, by default it reads BGR and if you want to read a grayscale image you need to use the second argument in imread. 是的,默认情况下它将读取BGR,如果您想读取灰度图像,则需要在imread中使用第二个参数。 From the docs : 文档

Read an image 读取图像

Use the function cv2.imread() to read an image. 使用函数cv2.imread()读取图像。 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. cv2.IMREAD_COLOR:加载彩色图像。 Any transparency of image will be neglected. 图像的任何透明度都将被忽略。 It is the default flag. 这是默认标志。
  2. cv2.IMREAD_GRAYSCALE : Loads image in grayscale mode cv2.IMREAD_GRAYSCALE:以灰度模式加载图像
  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. cv2.IMREAD_UNCHANGED:加载包括alpha通道在内的图像注意除了这三个标志,您可以分别简单地传递整数1、0或-1。

See the code below: 请参见下面的代码:

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

So, if you want to read in a grayscale image by default you need to have the second argument in imread as a 1, not 0. This subtle change to your code below should read in the same image format in both instances 因此,如果您希望默认情况下读取灰度图像,则需要将第二个参数的imread值读为1,而不是0。对您的以下代码进行的细微更改应在两种情况下都以相同的图像格式读取

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

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

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