2017-02-07 39 views
5

NumPy dizisinden bir PIL görüntüsü oluşturmak istiyorum.Bir NumPy dizisini PIL görüntüsüne dönüştürme

# 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') 

Ancak, baskı dışarı aşağıdaki verir: İşte benim girişimi

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

Ve kaydedilen görüntü saf kırmızı sahiptir sol üst, ancak tüm diğer pikseller siyah. Bu diğer pikseller neden NumPy dizisinde kendilerine atamış olduğum rengi tutmuyor?

Teşekkürler!

cevap

10

8-bitlik değerleri bekliyor RGB modu, bu yüzden sadece sorunu çözmek gerekir dizinizi döküm:

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) 
İlgili konular