2017-08-06 48 views
0

我想用Keras爲圖像提供網絡。我正在從互聯網上下載圖像並將它們存儲到一個numpy數組中。當我繪製單個圖像時,它會正確顯示。 作爲下一步,我創建了一個新的numpy數組,用於存儲單個圖像。但是,在該步驟中,圖像僅顯示爲黑色圖像。我想知道爲什麼發生這種情況?Keras和Numpy的圖像轉換

這裏是我的代碼:

import numpy as np 
import urllib.request 
import cv2 
from matplotlib import pyplot as plt 
from keras import backend as K 
%matplotlib inline 

file = "http://farm2.static.flickr.com/1353/1230897342_2bd7c7569f.jpg" 

# Read web file 
images_or = np.ndarray((1,128, 128,3), dtype=np.uint8) 
req = urllib.request.urlopen(file) 
arr = np.asarray(bytearray(req.read()), dtype=np.uint8) 
img = cv2.imdecode(arr,-1) # 'load it as it is' 
images_or[0] = cv2.resize(img,(128,128)) 

# Display image 
plt.imshow(images_or[0]) 
plt.show() 

# Format image 
images_or = images_or.astype(K.floatx()) 
images_or *= 0.96/255 
images_or += 0.02 

# Display image 
plt.imshow(images_or[0]) 
plt.show() 

# Reshape image 
images_or = images_or.reshape(images_or.shape[0], 3, 128, 128) 

# Copy image in another np.array 
A_train_test = np.ndarray((1, 3, 128, 128), dtype=np.uint8) 
A_train_test[0] = images_or[0] 

# Format image 
A_train_test = A_train_test.astype(K.floatx()) 
A_train_test *= 0.96/255 
A_train_test += 0.02 

# Reshape image 
A_train_test = A_train_test.reshape(A_train_test.shape[0], 128, 128, 3) 
image_xxx = A_train_test[0] 

plt.imshow(image_xxx) 
plt.show() 

非常感謝你提前, 安迪

回答

0

我需要改變命令的順序:

# Copy image in another np.array 
A_train_test = np.ndarray((1, 3, 128, 128), dtype=np.uint8) 
A_train_test = A_train_test.astype(K.floatx()) 
A_train_test[0][:] = images_or[0][:] 

問題就解決了。