2017-02-07 40 views
5

Tôi muốn tạo hình ảnh PIL từ một mảng NumPy. Đây là nỗ lực của tôi:Chuyển đổi một mảng NumPy thành hình ảnh 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') 

Tuy nhiên, in ra cho những điều sau đây:

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

Và hình ảnh được lưu có màu đỏ tinh khiết ở phía trên bên trái, nhưng tất cả các điểm ảnh khác là màu đen. Tại sao các pixel khác không giữ lại màu mà tôi đã gán cho chúng trong mảng NumPy?

Cảm ơn!

Trả lời

10

Các RGB chế độ dự kiến ​​giá trị 8-bit, vì vậy chỉ cần đúc mảng của bạn nên sửa chữa các vấn đề:

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) 
Các vấn đề liên quan