【发布时间】:2021-12-29 15:34:57
【问题描述】:
按照this answer on SO,我构建了这个python脚本来打乱文件夹内每个图像的像素:
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
上面的代码对某些图像非常有效,而对于其他图像则失败并显示此回溯消息:
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)
我不知道为什么会这样。所有图像均为 JPG 格式,分辨率为 500x400 像素。我正在使用 Python 3.10 版。是什么导致了这个问题?
【问题讨论】:
-
仔细检查失败的文件之一。我敢打赌它不是 500x400。
-
双重检查:文件为 500x400。分辨率不是原因,而是@aberry 建议的 RGBA 的 4 通道。
-
JPEG 不支持 RGBA,否则我会自己建议。但似乎它们可以是 CMYK,这是一种我从未遇到过的奇怪格式。您的文件的来源是什么?
-
来源是科学图像集 OASIS osf.io/6pnd7 — 免费图像的集合。一张不合适的图片是该系列的猴子 3 (#502)。
标签: python numpy image-processing