Importing PNG files into Numpy?

后端 未结 7 1379
轮回少年
轮回少年 2020-12-08 18:32

I have about 200 grayscale PNG images stored within a directory like this.

1.png
2.png
3.png
...
...
200.png

I want to import all the PNG i

相关标签:
7条回答
  • 2020-12-08 19:01

    If you are loading images, you are likely going to be working with one or both of matplotlib and opencv to manipulate and view the images.

    For this reason, I tend to use their image readers and append those to lists, from which I make a NumPy array.

    import os
    import matplotlib.pyplot as plt
    import cv2
    import numpy as np
    
    # Get the file paths
    im_files = os.listdir('path/to/files/')
    
    # imagine we only want to load PNG files (or JPEG or whatever...)
    EXTENSION = '.png'
    
    # Load using matplotlib
    images_plt = [plt.imread(f) for f in im_files if f.endswith(EXTENSION)]
    # convert your lists into a numpy array of size (N, H, W, C)
    images = np.array(images_plt)
    
    # Load using opencv
    images_cv = [cv2.imread(f) for f in im_files if f.endswith(EXTENSION)]
    # convert your lists into a numpy array of size (N, C, H, W)
    images = np.array(images_cv)
    

    The only difference to be aware of is the following:

    • opencv loads channels first
    • matplotlib loads channels last.

    So a single image that is 256*256 in size would produce matrices of size (3, 256, 256) with opencv and (256, 256, 3) using matplotlib.

    0 讨论(0)
提交回复
热议问题