Following this answer on SO, I build this python script to shuffle the pixels of each image inside a folder:
from PIL import Image
import numpy as np
import os
directory = "/my/path/images"
for file in os.listdir(directory):
filename = os.fsdecode(file)
if filename.endswith(".jpeg") or filename.endswith(".jpg"):
orig = Image.open(os.path.join(directory, filename))
orig_px = orig.getdata()
orig_px = np.reshape(orig_px, (orig.height * orig.width, 3))
np.random.shuffle(orig_px)
orig_px = np.reshape(orig_px, (orig.height, orig.width, 3))
res = Image.fromarray(orig_px.astype('uint8'))
res.save(rf'images-scrambled/scr-{filename}')
continue
else:
continue
Above code is working great for some images, for others it's failing with this traceback message:
Traceback (most recent call last):
File "/Users/user1/image_scrambler/03-image_scrambler-v2.py", line 19, in <module>
orig_px = np.reshape(orig_px, (orig.height * orig.width, 3))
File "<__array_function__ internals>", line 5, in reshape
File "/XYZ/site-packages/numpy/core/fromnumeric.py", line 298, in reshape
return _wrapfunc(a, 'reshape', newshape, order=order)
File "/XYZ/site-packages/numpy/core/fromnumeric.py", line 54, in _wrapfunc
return _wrapit(obj, method, *args, **kwds)
File "/XYZ/site-packages/numpy/core/fromnumeric.py", line 43, in _wrapit
result = getattr(asarray(obj), method)(*args, **kwds)
ValueError: cannot reshape array of size 800000 into shape (200000,3)
I don't know why this happens. All images are of JPG format and have a resolution of 500x400 pixels. I am using Python version 3.10. What's causing the issue?