2017-02-07 3 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

8 비트 값을 예상되는 RGB 모드, 그래서 그냥 문제를 해결해야 배열을 주조 :

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)