@@ -183,33 +183,59 @@ def set_colorbar(self, im, ax):
183183 self .colorbar = im , ax
184184
185185 def to_rgba (self , x , alpha = None , bytes = False ):
186- '''Return a normalized rgba array corresponding to *x*. If *x*
187- is already an rgb array, insert *alpha*; if it is already
188- rgba, return it unchanged. If *bytes* is True, return rgba as
189- 4 uint8s instead of 4 floats.
190- '''
191- if alpha is None :
192- _alpha = 1.0
193- else :
194- _alpha = alpha
186+ """
187+ Return a normalized rgba array corresponding to *x*.
188+
189+ In the normal case, *x* is a 1-D or 2-D sequence of scalars, and
190+ the corresponding ndarray of rgba values will be returned,
191+ based on the norm and colormap set for this ScalarMappable.
192+
193+ There is one special case, for handling images that are already
194+ rgb or rgba, such as might have been read from an image file.
195+ If *x* is an ndarray with 3 dimensions,
196+ and the last dimension is either 3 or 4, then it will be
197+ treated as an rgb or rgba array, and no mapping will be done.
198+ If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
199+ will be used to fill in the transparency. If the last dimension
200+ is 4, the *alpha* kwarg is ignored; it does not
201+ replace the pre-existing alpha. A ValueError will be raised
202+ if the third dimension is other than 3 or 4.
203+
204+ In either case, if *bytes* is *False* (default), the rgba
205+ array will be floats in the 0-1 range; if it is *True*,
206+ the returned rgba array will be uint8 in the 0 to 255 range.
207+
208+ Note: this method assumes the input is well-behaved; it does
209+ not check for anomalies such as *x* being a masked rgba
210+ array, or being an integer type other than uint8, or being
211+ a floating point rgba array with values outside the 0-1 range.
212+ """
213+ # First check for special case, image input:
195214 try :
196215 if x .ndim == 3 :
197216 if x .shape [2 ] == 3 :
217+ if alpha is None :
218+ alpha = 1
198219 if x .dtype == np .uint8 :
199- _alpha = np .array ( _alpha * 255 , np . uint8 )
220+ alpha = np .uint8 ( alpha * 255 )
200221 m , n = x .shape [:2 ]
201222 xx = np .empty (shape = (m ,n ,4 ), dtype = x .dtype )
202223 xx [:,:,:3 ] = x
203- xx [:,:,3 ] = _alpha
224+ xx [:,:,3 ] = alpha
204225 elif x .shape [2 ] == 4 :
205226 xx = x
206227 else :
207228 raise ValueError ("third dimension must be 3 or 4" )
208229 if bytes and xx .dtype != np .uint8 :
209230 xx = (xx * 255 ).astype (np .uint8 )
231+ if not bytes and xx .dtype == np .uint8 :
232+ xx = xx .astype (float ) / 255
210233 return xx
211234 except AttributeError :
235+ # e.g., x is not an ndarray; so try mapping it
212236 pass
237+
238+ # This is the normal case, mapping a scalar array:
213239 x = ma .asarray (x )
214240 x = self .norm (x )
215241 x = self .cmap (x , alpha = alpha , bytes = bytes )
0 commit comments