zoukankan      html  css  js  c++  java
  • 【数字图像处理】OpenCV中cv2.imread()与PIL中Image.open()的差别

    cv2.imread()与PIL中Image.open()两个函数都是用来读取图像,但是在使用过程存在一些差别

    1. 首先,从导入库方面看:

    # opencv-python
    import cv2
    
    # PIL
    from PIL import Image

    2. 读取图像

    # opencv-python
    img = cv2.imread('' ---.jpg'')
    img = cv2.imread('' ---.jpg'', flages=cv2.IMREAD_GRAYSCALE)     # flags是可选读入模式,如灰度图等,默认为None
    
    # PIL
    img = Image.open("---.jpg")
    img = Image.open("---.jpg", mode=‘r’ ) # mode只能并且默认是‘r’,未查阅到相关资料,暂时不清楚具体代表什么。

    值得注意的是,在文档中对Image.open()函数的描述如下:

       Opens and identifies the given image file.
    
        This is a lazy operation; this function identifies the file, but
        the file remains open and the actual image data is not read from
        the file until you try to process the data (or call the
        :py:meth:`~PIL.Image.Image.load` method).  See
        :py:func:`~PIL.Image.new`. See :ref:`file-handling`.

    Image.open()函数只是保持了图像被读取的状态,但是图像的真实数据并未被读取,因此如果对需要操作图像每个元素,如输出某个像素的RGB值等,需要执行对象的load()方法读取数据。具体如下:

    img = Image.open("lena.jpg")
    img = img.load()
    print(img[0,0])
    # result:(255, 201, 166)

    3. 默认读入图像通道

      对于Image.open()函数默认真彩图像读取通道顺序为RGB,而cv2.imread()则是BGR。同时,当图像格式为RGBA时,Image.open(‘---.jpg’)读取的格式为RGBA(其中A表示图像的alpha通道,即RGBA共四个通道),而cv2.imread('---.jpg')读取的格式是BGR,只有三个通道。

    (1)

        import cv2
        from PIL import Image
        img = cv2.imread(r"F:DailyPracticeAffectiveComputingck+_dataset1_17_0.png")
        b, g, r = cv2.split(img)
        img = Image.open(r"F:DailyPracticeAffectiveComputingck+_dataset1_17_0.png")
        print(img.mode)

    结果如下:

    RGBA

    (2)

        import cv2
        from PIL import Image
        img = cv2.imread(r"----.jpg")
        b, g, r, _ = cv2.split(img)
        print(img)
        img = Image.open(r"----.jpg"")
        print(img.mode)

    报错信息如下:

    Traceback (most recent call last):
      File "(此处为当前运行脚本名称及路径,已被删除)", line 122, in <module>
        b, g, r, _ = cv2.split(img)
    ValueError: not enough values to unpack (expected 4, got 3)

    报错提示 cv2.split(img)只返回三个返回参数,但是‘=’左边却有四个接收变量。而(1)是正确的,故 cv2.imread(r"----.jpg")对于RGBA图像只读取了BGR三个通道。

    参考文献

    【1】https://www.cnblogs.com/lyrichu/p/9124504.html

  • 相关阅读:
    ensp抓包只有蓝色的点闪烁没有跳出wireshark
    QuartusII 13.1编译通过,波形仿真报错Error: near "/": syntax error, unexpected '/', expecting ')'
    安装Multisim时出现No software will be installed or removed无法安装
    JavaScript实现页面实时显示时间
    css图片覆盖文字 点击显示文字
    php魔术方法——属性重载方法
    php魔术方法——构造函数和析构函数
    将含有父ID的列表转成树
    分割gbk中文出现乱码的问题解决
    json_encode如何防止汉字转义成unicode
  • 原文地址:https://www.cnblogs.com/chen-hw/p/11693806.html
Copyright © 2011-2022 走看看