展平RGB图像阵列

时间:2017-04-24 07:26:44

标签: arrays rgb flatten

我有129756个RGB图像(100X187),我想将其转换为(m,n)数组。

我使用了这段代码:

for i in range(len(imlist)):
 img =np.array(Image.open('/home/fatmasaid/new_flicker_data_resized_color'+'//'+imlist[i]))
 immatrix =np.array(img.flatten()) 
print (immatrix.shape )

我得到了(56100,)

但是,我需要一个具有以下尺寸的数组:(129756,56100)

我怎样才能做到这一点?

我也试过这段代码:

immatrix = np.empty((len(imlist),3, 187, 100), dtype="float32")
l=len(imlist)

for i in range(l):
    img = Image.open(path2 + '/'+ imlist[i])
    width, height=img.size


    r=np.zeros((187,100),dtype=float)
    g=np.zeros((187,100),dtype=float)
    b=np.zeros((187,100),dtype=float)

    for y in range(height-1):
        for x in range(width-1):
            rgb = img.getpixel((x,y))

            rgb=(rgb[0],rgb[1],rgb[2],);

            r[y][x]=rgb[0]
            g[y][x]=rgb[1]
            b[y][x]=rgb[2]

    AImg=[r,g,b]

    arr = np.asarray(AImg, dtype="float32")
    immatrix[i, :, :, :] = arr

    if i % 5000 == 0:
        print (i)
print (immatrix.shape)

但是我收到了这个错误:

索引100超出轴0的大小为100

1 个答案:

答案 0 :(得分:0)

batch_array = np.empty([0])
for i in range(len(imlist)): 
    img = np.array(Image.open('/home/fatmasaid/new_flicker_data_resized_color'+'//'+imlist[i])) 
    immatrix =np.array(img.flatten())   
    batch_array = np.append(batch_array, immatrix) 
print (immatrix.shape )

您可以尝试将immatrix附加到另一个数组。目前,您正在循环的每次迭代中刷新immatrix

另一种方式是:

batch_array = np.empty([0])
for i in range(len(imlist)): 
    img = np.array(Image.open('/home/fatmasaid/new_flicker_data_resized_color'+'//'+imlist[i])) 

    batch_array = np.append(batch_array, img)

batch_array = batch_array.flatten()

batch_array = np.reshape(batch_array, (len(imlist), len(batch_array)/len(imlist)))
print (immatrix.shape )