2017-02-07 37 views
5

Chcę utworzyć obraz PIL z tablicy NumPy. Oto moja próba:Konwertowanie tablicy NumPy na obraz PIL

# Create a NumPy array, which has four elements. The top-left should be pure red, the top-right should be pure blue, the bottom-left should be pure green, and the bottom-right should be yellow 
pixels = np.array([[[255, 0, 0], [0, 255, 0]], [[0, 0, 255], [255, 255, 0]]]) 

# Create a PIL image from the NumPy array 
image = Image.fromarray(pixels, 'RGB') 

# Print out the pixel values 
print image.getpixel((0, 0)) 
print image.getpixel((0, 1)) 
print image.getpixel((1, 0)) 
print image.getpixel((1, 1)) 

# Save the image 
image.save('image.png') 

jednak wydruk daje następujące:

(255, 0, 0) 
(0, 0, 0) 
(0, 0, 0) 
(0, 0, 0) 

I zapisany obraz ma czysty czerwony w lewym górnym rogu, ale wszystkie pozostałe piksele są czarne. Dlaczego te inne piksele nie zachowują koloru przypisanego im w tablicy NumPy?

Dzięki!

Odpowiedz

10

Tryb RGB spodziewa wartości 8-bitowych, więc po prostu rzucając swoją tablicę powinno rozwiązać problem:

In [25]: image = Image.fromarray(pixels.astype('uint8'), 'RGB') 
    ...: 
    ...: # Print out the pixel values 
    ...: print image.getpixel((0, 0)) 
    ...: print image.getpixel((0, 1)) 
    ...: print image.getpixel((1, 0)) 
    ...: print image.getpixel((1, 1)) 
    ...: 
(255, 0, 0) 
(0, 0, 255) 
(0, 255, 0) 
(255, 255, 0)