Python PIL方式打开的图片判断维度

1. PIL方式打开的图片判断维度

     好久没更新啦,哈哈哈~~!今天跟宝宝们分享一篇如何判断灰度图像和彩色图像维度的方法。我们在读取灰度图像和彩色图像时,发现读取出来的图片维度不同,当我们要做后续操作的时候,很可能去人工判断,那样显得自己憨憨的,今天就帮各位宝宝解决这个问题啦!!!

  读取灰度图片,获取的格式是:(height, width),此时就只有两维了,灰度图像channel为1,就会被省略掉。读取彩色图片,获取的格式是:(height,width,channel),此时channel一般为3,会被保留下来。那么问题来了,在Python里面好像还没提供直接获取维度的方法,最多提供了Image.shape,单这就只能获取上诉说的(height, width)或(height,width,channel)这种格式信息,而不是直接得到一个2或者3。

  好啦,不多说啦,直接上code......

2. 例子

2.1 code

import numpy as np
from PIL import Image
from torchvision import transforms


def get_Image_dim_len(image_dir):
    image = Image.open(image_dir)
    image_dim_len = len(np.array(image).shape)
    image.show()
    print("The dim of Image: ", image_dim_len)



if __name__ == '__main__':
    # 彩色图像
    image_color = './test_datasets/1.jpg'
    get_Image_dim_len(image_color)
    # # 灰度图像
    # image_gray = './test_datasets/2.jpg'
    # get_Image_dim_len(image_gray)

2.2 结果展示

 

              (a)彩色图像                             (b)灰度图像

图(a)的输出为:The dim of Image:  3

图(b)的输出为:The dim of Image:  2

3. 总结

  努力去爱周围的每一个人,付出,不一定有收获,但是不付出就一定没有收获! 给街头卖艺的人零钱,不和深夜还在摆摊的小贩讨价还价。愿我的博客对你有所帮助(*^▽^*)(*^▽^*)!

   如果客官喜欢小生的园子,记得关注小生哟,小生会持续更新(#^.^#)(#^.^#)。

  

  

原文地址:https://www.cnblogs.com/haifwu/p/13408277.html