I have this obscure behaviour of python that I am trying to understand. I am pretty sure it is not a bug, but I can't really explain WHY it is behaving like this. I am trying to load a few images into a list and then manipulate them.
Here is a minimal example:
import numpy as np
from PIL import Image
import os
DATA_URL = ('./images/')
def load_data():
data_internal = list()
for root, dirs, files in os.walk(DATA_URL, topdown=False):
for name in files:
with Image.open(DATA_URL + name) as f:
data_internal.append(f)
return data_internal
data = load_data()
print(data[0])
print(np.array(data[0]))
This code produces the following:
> <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2x2 at 0x1EDCC735708>
> <PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2x2 at 0x1EDCC735708>
so
data[0]
and
np.array(data[0])
are exactly the same thing.
However, if I add a line to print
f
as a
np.array()
within the read-in, behaviour changes:
import numpy as np
from PIL import Image
import os
DATA_URL = ('./images/')
def load_data():
data_internal = list()
for root, dirs, files in os.walk(DATA_URL, topdown=False):
for name in files:
with Image.open(DATA_URL + name) as f:
data_internal.append(f)
print(np.array(data_internal[0]))
return data_internal
data = load_data()
print(data[0])
print(np.array(data[0]))
The output of that example is
> [[[146 135 129]
> [145 134 128]]
>
> [[148 137 133]
> [148 137 133]]]
>
><PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=2x2 at 0x261491DEF48>
>
>[[[146 135 129]
> [145 134 128]]
>
> [[148 137 133]
> [148 137 133]]]
as I would expect.
Can anyone please tell me, why the mere access of the mutated (cast to numpy array) list entry makes this possible?
Thanks a lot & best regards