Python 将PNG文件导入Numpy?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31386096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:54:23  来源:igfitidea点击:

Importing PNG files into Numpy?

pythonimagenumpypng

提问by pbu

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

我有大约 200 张灰度 PNG 图像存储在这样的目录中。

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

I want to import all the PNG images as NumPy arrays. How can I do this?

我想将所有 PNG 图像导入为 NumPy 数组。我怎样才能做到这一点?

采纳答案by spoorcc

Using just scipy, glob and having PIL installed (pip install pillow) you can use scipy's imreadmethod:

仅使用 scipy、glob 并安装了 PIL ( pip install pillow) 您就可以使用 scipy 的imread方法:

from scipy import misc
import glob

for image_path in glob.glob("/home/adam/*.png"):
    image = misc.imread(image_path)
    print image.shape
    print image.dtype

UPDATE

更新

According to the doc, scipy.misc.imreadis deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imread instead. See the answer by Charles.

根据文档,scipy.misc.imread从 SciPy 1.0.0 开始不推荐使用,并将在 1.2.0 中删除。考虑使用imageio.imread instead. 请参阅Charles 的回答

回答by pbu

I changed a bit and it worked like this, dumped into one single array, provided all the images are of same dimensions.

我做了一些改变,它像这样工作,转储到一个数组中,前提是所有图像的尺寸都相同。

png = []
for image_path in glob.glob("./train/*.png"):
    png.append(misc.imread(image_path))    

im = np.asarray(png)

print 'Importing done...', im.shape

回答by Charles

Bit late to the party, but the current answer is now deprecated.

聚会有点晚了,但现在不推荐使用当前的答案。

According to the doc, scipy.misc.imreadis deprecated starting SciPy 1.0.0, and will be removed in 1.2.0. Consider using imageio.imreadinstead.

根据文档scipy.misc.imread从 SciPy 1.0.0 开始不推荐使用,并将在 1.2.0 中删除。考虑imageio.imread改用。

Example:

例子:

import imageio

im = imageio.imread('my_image.png')
print(im.shape)

You can also use imageio to load from fancy sources:

您还可以使用 imageio 从花哨的来源加载:

im = imageio.imread('http://upload.wikimedia.org/wikipedia/commons/d/de/Wikipedia_Logo_1.0.png')

Edit:

编辑:

To load all of the *.pngfiles in a specific folder, you could use the globpackage:

要加载*.png特定文件夹中的所有文件,您可以使用该glob包:

import imageio
import glob

for im_path in glob.glob("path/to/folder/*.png"):
     im = imageio.imread(im_path)
     print(im.shape)
     # do whatever with the image here

回答by mrk

This can also be done with the Imageclass of the PIL library:

这也可以通过PIL 库Image类来完成:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata()might not be needed - np.array(im_frame)should also work

注意:.getdata()可能不需要 -np.array(im_frame)也应该工作

回答by n1k31t4

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

如果您正在加载图片,你可能要与一个或两个的合作matplotlibopencv操纵和查看图像。

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

出于这个原因,我倾向于使用他们的图像阅读器并将它们附加到列表中,我从中制作了一个 NumPy 数组。

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.
  • opencv首先加载频道
  • matplotlib最后加载通道。

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.

因此,大小为 256*256 的单个图像将使用 opencv 生成大小为 (3, 256, 256) 的矩阵,使用 matplotlib 生成大小为 (256, 256, 3) 的矩阵。

回答by Nir

Using a (very) commonly used package is prefered:

最好使用(非常)常用的包:

import matplotlib.pyplot as plt
im = plt.imread('image.png')

回答by Kolibril

I like the build-in pathlib libary because of quick options like directory= Path.cwd()Together with opencv it's quite easy to read pngs to numpy arrays. In this example you can even check the prefix of the image.

我喜欢内置的 pathlib 库,因为它提供了快速选项,例如directory= Path.cwd()与 opencv 一起使用,可以很容易地将 png 读取到 numpy 数组。在这个例子中,您甚至可以检查图像的前缀。

from pathlib import Path
import cv2
prefix = "p00"
suffix = ".png"
directory= Path.cwd()
file_names= [subp.name for subp in directory.rglob('*') if  (prefix in subp.name) & (suffix == subp.suffix)]
file_names.sort()
print(file_names)

all_frames= []
for file_name in file_names:
    file_path = str(directory / file_name)
    frame=cv2.imread(file_path)
    all_frames.append(frame)
print(type(all_frames[0]))
print(all_frames[0] [1][1])

Output:

输出:

['p000.png', 'p001.png', 'p002.png', 'p003.png', 'p004.png', 'p005.png', 'p006.png', 'p007.png', 'p008.png', 'p009.png']
<class 'numpy.ndarray'>
[255 255 255]