我想将.gif文件转换为4D数组/ RGB值的3D数组。
我尝试过PIL,但这似乎只让我把gif读成灰度图像。
来自numpy的ndimage
没有那个问题,但只会导致gif的第一帧。
.gif我试图转换,出于测试目的,是
在第一帧的顶部红色增加,在fisrt帧的一侧增加绿色,并且随着帧的增加,在左上角增加蓝色。
PIL给了我
[[[ 0 3 5 6 8]
[ 7 12 12 12 12]
[ 9 12 12 12 12]
[10 12 12 12 12]
[11 12 12 12 12]]
[[ 1 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]]
[[ 2 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]]
[[ 4 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]
[12 12 12 12 12]]]
而numpy给了我
[[[ 0 0 0]
[ 20 0 0]
[ 40 0 0]
[ 60 0 0]
[ 80 0 0]]
[[ 0 20 0]
[255 255 255]
[255 255 255]
[255 255 255]
[255 255 255]]
[[ 0 40 0]
[255 255 255]
[255 255 255]
[255 255 255]
[255 255 255]]
[[ 0 60 0]
[255 255 255]
[255 255 255]
[255 255 255]
[255 255 255]]
[[ 0 80 0]
[255 255 255]
[255 255 255]
[255 255 255]
[255 255 255]]]
这两者都不是我想要的。
答案 0 :(得分:2)
import numpy as np
from PIL import Image, ImageSequence
img = Image.open('test.gif')
frames = np.array([np.array(frame.copy().convert('RGB').getdata(),dtype=np.uint8).reshape(frame.size[1],frame.size[0],3) for frame in ImageSequence.Iterator(img)])
输出:
(frame_num * frame_width * frame_height * 3(RGB))
[array([[[ 0, 0, 0],
[ 20, 0, 0],
[ 40, 0, 0],
[ 60, 0, 0],
[ 80, 0, 0]],
[[ 0, 20, 0],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[ 0, 40, 0],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[ 0, 60, 0],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[ 0, 80, 0],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8),
array([[[ 0, 0, 20],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8),
array([[[ 0, 0, 40],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8),
array([[[ 0, 0, 60],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]],
[[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255],
[255, 255, 255]]], dtype=uint8)]