2017-02-07 12 views
5

NumPy配列からPIL画像を作成したいとします。ここに私の試みは次のとおりです。NumPy配列を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') 

しかし、プリントアウトには、以下を与える:

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

、保存された画像は、左上に純粋な赤を持っていますが、他のすべてのピクセルは黒です。これらの他のピクセルがNumPy配列に割り当てられている色を保持していないのはなぜですか?

ありがとうございます!

答えて

10

RGBモードは、8ビットの値を期待しているので、ちょうどあなたの配列をキャストすると、問題を修正する必要があります。

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) 
関連する問題