2017-02-07 8 views
5

पर एक NumPy सरणी को कनवर्ट करना मैं NumPy सरणी से एक पीआईएल छवि बनाना चाहता हूँ।एक PUM छवि

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