python读取图像的几种方式

python读取图像的几种方式

本文介绍几种基于python的图像读取方式:

  • 基于PIL库的图像读取、保存和显示
  • 基于opencv-python的图像读取、保存和显示
  • 基于matplotlib的图像读取、保存和显示
  • 基于scikit-image的图像读取、保存和显示
  • 基于imageio的图像读取、保存和显示
  • 安装方式基本使用pip即可:

    pip install pillow
    pip install scikit-image
    pip install matplotlib 
    pip install opencv-python
    pip install numpy scipy scikit-learn
    

    基于PIL库的图像读取、保存和显示

    from PIL import Image
    

    设置图片名字

    img_path = './test.png'
    

    用PIL的open函数读取图片

    img = Image.open(img_path)
    

    读进来是一个Image对象

    img
    

    请添加图片描述

    查看图片的mode

    img.mode
    
    'RGB'
    

    用PIL函数convert将彩色RGB图像转换为灰度图像

    img_g = img.convert('L')
    
    img_g.mode
    
    'L'
    
    img_g.save('./test_gray.png')
    

    使用PIL库的crop函数可对图像进行裁剪

    img_c = img.crop((100,50,200,150))
    img_c
    

    请添加图片描述

    图像旋转

    img.rotate(45)
    

    请添加图片描述

    在图像上添加文字

    from PIL import ImageDraw, ImageFont
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype('/home/fsf/Fonts/ariali.ttf',size=24)
    draw.text((10,5), "This is a picture of sunspot.", font=font)
    del draw
    img
    

    请添加图片描述

    基于opencv-python的图像读取、保存和显示

    import cv2
    
    img = cv2.imread('./test.png')
    

    使用cv2都进来是一个numpy矩阵,像素值介于0~255,可以使用matplotlib进行展示

    img.min(), img.max()
    
    (0, 255)
    
    import matplotlib.pyplot as plt
    plt.imshow(img)
    plt.axis('off')
    plt.show()
    

    基于matplotlib的图像读取、显示和保存

    import matplotlib.image as mpimg
    
    img = mpimg.imread('./test.png')
    
    img.min(),img.max()
    
    (0.0, 1.0)
    

    像素值介于0~1之间,可以使用如下方法进行展示

    import matplotlib.pyplot as plt
    plt.imshow(img,interpolation='spline16')
    plt.axis('off')
    plt.show()
    

    注意:matplotlib在进行imshow时,可以进行不同程度的插值,当绘制图像很小时,这些方法比较有用,如上所示就是用了样条插值。

    基于scikit-image的图像读取、保存和显示

    from skimage.io import imread, imsave, imshow
    
    img = imread('./test.png')
    

    这个和opencv-python类似,读取进来也是numpy矩阵,像素值介于0~255之间

    img.min(), img.max()
    
    (0, 255)
    
    import matplotlib.pyplot as plt
    plt.imshow(img,interpolation='spline16')
    plt.axis('off')
    plt.show()
    

    基于imageio的图像读取、显示和保存

    import imageio
    
    img = imageio.imread('./test.png')
    
    img.min(), img.max()
    
    (0, 255)
    

    这个和opencv-python、scikit-image类似,读取进来也都是numpy矩阵,像素值介于0~255之间

    import matplotlib.pyplot as plt
    plt.imshow(img,interpolation='spline16')
    plt.axis('off')
    plt.show()
    

    来源:花生david

    物联沃分享整理
    物联沃-IOTWORD物联网 » python读取图像的几种方式

    发表评论