@@ -461,8 +461,6 @@ def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
461461 if not (A .ndim == 2 or A .ndim == 3 and A .shape [- 1 ] in (3 , 4 )):
462462 raise ValueError (f"Invalid shape { A .shape } for image data" )
463463
464- float_rgba_in = A .ndim == 3 and A .shape [- 1 ] == 4 and A .dtype .kind == 'f'
465-
466464 # if antialiased, this needs to change as window sizes
467465 # change:
468466 interpolation_stage = self ._interpolation_stage
@@ -566,13 +564,22 @@ def get_scaled_dtype(A):
566564 # Resample in premultiplied alpha space. (TODO: Consider
567565 # implementing premultiplied-space resampling in
568566 # span_image_resample_rgba_affine::generate?)
569- if float_rgba_in and np .ndim (alpha ) == 0 and np .any (A [..., 3 ] < 1 ):
570- # Do not modify original RGBA input
571- A = A .copy ()
572- A [..., :3 ] *= A [..., 3 :]
567+ # Multiplying the whole array and then restoring the alpha channel
568+ # is faster than an in-place multiply of the strided A[..., :3]
569+ # view. If alpha is uniformly 1, premultiplication can be skipped.
570+ alpha_in = A [..., 3 ]
571+ if (alpha_in != 1 ).any ():
572+ A = A * alpha_in [..., None ]
573+ A [..., 3 ] = alpha_in
573574 res = _resample (self , A , out_shape , t )
574- np .divide (res [..., :3 ], res [..., 3 :], out = res [..., :3 ],
575- where = res [..., 3 :] != 0 )
575+ # Demultiply. Zeroes in the divisor are replaced by ones,
576+ # which leaves the corresponding (premultiplied) RGB values
577+ # untouched. Dividing the whole contiguous array is several
578+ # times faster than np.divide(..., where=...) into the strided
579+ # res[..., :3] view.
580+ alpha_out = res [..., 3 ].copy ()
581+ res /= np .where (alpha_out != 0 , alpha_out , 1 )[..., None ]
582+ res [..., 3 ] = alpha_out
576583 if post_apply_alpha :
577584 res [..., 3 ] *= alpha
578585
0 commit comments