Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 09a0f4c

Browse files
committed
Faster conversion for RGBA arrays; more tests.
1 parent 72f34be commit 09a0f4c

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

lib/matplotlib/colors.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,6 +218,22 @@ def to_rgba_array(c, alpha=None):
218218
return np.array([to_rgba(c, alpha)], float)
219219
except (ValueError, TypeError):
220220
pass
221+
# Special-case inputs that are already arrays, for performance. (If the
222+
# array has the wrong kind or shape, raise the error during one-at-a-time
223+
# conversion.)
224+
if (isinstance(c, np.ndarray) and c.dtype.kind in "if"
225+
and c.ndim == 2 and c.shape[1] in [3, 4]):
226+
if c.shape[1] == 3:
227+
result = np.column_stack([c, np.zeros(len(c))])
228+
result[:, -1] = alpha if alpha is not None else 1.
229+
elif c.shape[1] == 4:
230+
result = c.copy()
231+
if alpha is not None:
232+
result[:, -1] = alpha
233+
if np.any((result < 0) | (result > 1)):
234+
raise ValueError("RGBA values should be within 0-1 range")
235+
return result
236+
# Convert one at a time.
221237
result = np.empty((len(c), 4), float)
222238
for i, cc in enumerate(c):
223239
result[i] = to_rgba(cc, alpha)

lib/matplotlib/tests/test_colors.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -633,6 +633,8 @@ def test_conversions():
633633
assert_array_equal(mcolors.to_rgba_array("none"), np.zeros((0, 4)))
634634
# alpha is properly set.
635635
assert_equal(mcolors.to_rgba((1, 1, 1), .5), (1, 1, 1, .5))
636+
# builtin round differs between py2 and py3.
637+
assert_equal(mcolors.to_hex((.7, .7, .7)), "#b2b2b2ff")
636638

637639

638640
if __name__ == '__main__':

0 commit comments

Comments
 (0)