Cupy as drop-in replacement for numpy#

Cupy can be used as a drop-in replacement for numpy

try:
    import cupy as xp
except:
    import numpy as xp

import numpy as np

xp
<module 'cupy' from 'C:\\Users\\haase\\mambaforge\\envs\\cupy39_1\\lib\\site-packages\\cupy\\__init__.py'>
from skimage.io import imread, imshow
image = imread("../../data/blobs.tif")
imshow(image)
<matplotlib.image.AxesImage at 0x24692cc0460>
../_images/a70e610a999f6faabad65a538eeb89d349bd72f36ffeb67e6a01a9484ea4cbe1.png
xp_image = xp.asarray(image)

Cupy images cannot be shown using imshow. This line would lead to an error:

# imshow(xp_image)

We need to convert the image back to a numpy array before showing it.

if np == xp:
    np_image = xp_image
else:
    np_image = xp.asnumpy(xp_image)

imshow(np_image)
<matplotlib.image.AxesImage at 0x24692ef85e0>
../_images/a70e610a999f6faabad65a538eeb89d349bd72f36ffeb67e6a01a9484ea4cbe1.png