Updates dieser Seite:
In diesem Kapitel lernen wir einen Weg, um Bilder in Python auf Pixelebene zu verarbeiten, so dass wir z.B. Konvolutionen ausprobieren können.
Wir verwenden hier die Python-Bibliothek Pillow, um Bilder zu speichern und zu verarbeiten. Pillow ist das Nachfolgeprojekt der Python Image Library (PIL). Es wird aber immer noch die Abkürzung PIL im Code verwendet.
Siehe auch:
Um ein Bild aus dem Internet zu beziehen, benötigen wir außerdem BytesIO und requests.
Wir wandeln die Daten gleich in einem NumPy-Array um, damit wir damit in Keras arbeiten können. Sie sehen, dass es sich um ein Bild der Größe 600x450 mit 3 Kanälen (R, G, B) handelt.
from PIL import Image
from io import BytesIO
import numpy as np
import requests
url = "https://upload.wikimedia.org/wikipedia/commons/thumb/3/3f/Edward_Snowden_2013-10-9_%281%29_%28cropped%29.jpg/450px-Edward_Snowden_2013-10-9_%281%29_%28cropped%29.jpg"
response = requests.get(url)
img = Image.open(BytesIO(response.content))
img.load
idat = np.asarray(img)
print("Shape:", idat.shape)
idat[:2]# Testausgabe
Shape: (600, 450, 3)
array([[[214, 154, 118], [216, 156, 120], [217, 157, 121], ..., [200, 139, 111], [201, 140, 112], [201, 140, 112]], [[217, 157, 121], [217, 157, 121], [217, 157, 121], ..., [200, 139, 111], [201, 140, 112], [201, 140, 112]]], dtype=uint8)
Wir schauen uns das Image-Objekt an.
print(img)
<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=450x600 at 0x7FE5734B93D0>
img.mode
'RGB'
img.size
(450, 600)
Im Package matplotlib gibt es die Funktion imshow (image show), um Bilder darzustellen.
from matplotlib.pyplot import imshow
imshow(img)
Bad key "text.kerning_factor" on line 4 in /Users/kipp/anaconda3/envs/nndl/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/_classic_test_patch.mplstyle. You probably need to get an updated matplotlibrc file from https://github.com/matplotlib/matplotlib/blob/v3.1.3/matplotlibrc.template or from the matplotlib source distribution
<matplotlib.image.AxesImage at 0x7fe574554a10>
Tatsächlich kann man das auch so ausgeben:
img