如何将numpy数组转换为(并显示)图像?

问题:如何将numpy数组转换为(并显示)图像?

我因此创建了一个数组:

import numpy as np
data = np.zeros( (512,512,3), dtype=np.uint8)
data[256,256] = [255,0,0]

我要执行的操作是在512×512图像的中心显示一个红点。(至少从…开始,我想我可以从那里找出其余的内容)

I have created an array thusly:

import numpy as np
data = np.zeros( (512,512,3), dtype=np.uint8)
data[256,256] = [255,0,0]

What I want this to do is display a single red dot in the center of a 512×512 image. (At least to begin with… I think I can figure out the rest from there)


回答 0

您可以使用PIL创建(并显示)图像:

from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()

You could use PIL to create (and display) an image:

from PIL import Image
import numpy as np

w, h = 512, 512
data = np.zeros((h, w, 3), dtype=np.uint8)
data[0:256, 0:256] = [255, 0, 0] # red patch in upper left
img = Image.fromarray(data, 'RGB')
img.save('my.png')
img.show()

回答 1

以下应该工作:

from matplotlib import pyplot as plt
plt.imshow(data, interpolation='nearest')
plt.show()

如果您使用的是Jupyter笔记本/实验室,请在导入matplotlib之前使用以下内联命令:

%matplotlib inline 

The following should work:

from matplotlib import pyplot as plt
plt.imshow(data, interpolation='nearest')
plt.show()

If you are using Jupyter notebook/lab, use this inline command before importing matplotlib:

%matplotlib inline 

回答 2

最短的路径是使用scipy,如下所示:

from scipy.misc import toimage
toimage(data).show()

这也需要安装PIL或Pillow。

同样需要PIL或Pillow但可以调用其他查看器的类似方法是:

from scipy.misc import imshow
imshow(data)

Shortest path is to use scipy, like this:

from scipy.misc import toimage
toimage(data).show()

This requires PIL or Pillow to be installed as well.

A similar approach also requiring PIL or Pillow but which may invoke a different viewer is:

from scipy.misc import imshow
imshow(data)

回答 3

使用pygame,您可以打开一个窗口,以像素阵列的形式获取表面,然后从那里进行操作。但是,您需要将numpy数组复制到Surface数组中,这比在pygame Surface本身上进行实际图形操作要慢得多。

Using pygame, you can open a window, get the surface as an array of pixels, and manipulate as you want from there. You’ll need to copy your numpy array into the surface array, however, which will be much slower than doing actual graphics operations on the pygame surfaces themselves.


回答 4

如何使用示例显示存储在numpy数组中的图像(在Jupyter笔记本中有效)

我知道有更简单的答案,但是这一答案将使您了解如何从numpy数组中淹没图像。

加载示例

from sklearn.datasets import load_digits
digits = load_digits()
digits.images.shape   #this will give you (1797, 8, 8). 1797 images, each 8 x 8 in size

显示一幅图像的阵列

digits.images[0]
array([[ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.],
       [ 0.,  0., 13., 15., 10., 15.,  5.,  0.],
       [ 0.,  3., 15.,  2.,  0., 11.,  8.,  0.],
       [ 0.,  4., 12.,  0.,  0.,  8.,  8.,  0.],
       [ 0.,  5.,  8.,  0.,  0.,  9.,  8.,  0.],
       [ 0.,  4., 11.,  0.,  1., 12.,  7.,  0.],
       [ 0.,  2., 14.,  5., 10., 12.,  0.,  0.],
       [ 0.,  0.,  6., 13., 10.,  0.,  0.,  0.]])

创建空的10 x 10子图以可视化100张图像

import matplotlib.pyplot as plt
fig, axes = plt.subplots(10,10, figsize=(8,8))

绘制100张图像

for i,ax in enumerate(axes.flat):
    ax.imshow(digits.images[i])

结果:

怎么axes.flat办? 它创建了numpy枚举器,因此您可以在轴上迭代以在其上绘制对象。 例:

import numpy as np
x = np.arange(6).reshape(2,3)
x.flat
for item in (x.flat):
    print (item, end=' ')

How to show images stored in numpy array with example (works in Jupyter notebook)

I know there are simpler answers but this one will give you understanding of how images are actually drawn from a numpy array.

Load example

from sklearn.datasets import load_digits
digits = load_digits()
digits.images.shape   #this will give you (1797, 8, 8). 1797 images, each 8 x 8 in size

Display array of one image

digits.images[0]
array([[ 0.,  0.,  5., 13.,  9.,  1.,  0.,  0.],
       [ 0.,  0., 13., 15., 10., 15.,  5.,  0.],
       [ 0.,  3., 15.,  2.,  0., 11.,  8.,  0.],
       [ 0.,  4., 12.,  0.,  0.,  8.,  8.,  0.],
       [ 0.,  5.,  8.,  0.,  0.,  9.,  8.,  0.],
       [ 0.,  4., 11.,  0.,  1., 12.,  7.,  0.],
       [ 0.,  2., 14.,  5., 10., 12.,  0.,  0.],
       [ 0.,  0.,  6., 13., 10.,  0.,  0.,  0.]])

Create empty 10 x 10 subplots for visualizing 100 images

import matplotlib.pyplot as plt
fig, axes = plt.subplots(10,10, figsize=(8,8))

Plotting 100 images

for i,ax in enumerate(axes.flat):
    ax.imshow(digits.images[i])

Result:

What does axes.flat do? It creates a numpy enumerator so you can iterate over axis in order to draw objects on them. Example:

import numpy as np
x = np.arange(6).reshape(2,3)
x.flat
for item in (x.flat):
    print (item, end=' ')

回答 5

例如,使用枕头的fromarray:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()

Using pillow’s fromarray, for example:

from PIL import Image
from numpy import *

im = array(Image.open('image.jpg'))
Image.fromarray(im).show()

回答 6

Python图像库可以显示使用numpy的阵列的图像。查看此页面以获取示例代码:

编辑:正如该页面底部的注释所述,您应该检查最新的发行说明,这会使此过程变得更加简单:

http://effbot.org/zone/pil-changes-116.htm

The Python Imaging Library can display images using Numpy arrays. Take a look at this page for sample code:

EDIT: As the note on the bottom of that page says, you should check the latest release notes which make this much simpler:

http://effbot.org/zone/pil-changes-116.htm


回答 7

使用matplotlib进行补充。我发现在执行计算机视觉任务时很方便。假设您有dtype = int32的数据

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))

Supplement for doing so with matplotlib. I found it handy doing computer vision tasks. Let’s say you got data with dtype = int32

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))