sha_hla
sha_hla

Reputation: 344

How resize images when those converted to numpy array

Consider we only have images as.npy file. Is it possible to resizing images without converting their to images (because I'm looking for a way that is fast when run the code). for more info, I asked the way without converting to image, I have images but i don't want use those in code, because my dataset is too large and running with images is so slow, on the other hand, Im not sure which size is better for my imeges, So Im looking for a way that first convert images to npy and save .npy file and then preprocess npy file, for example resize the dimension of images.

Upvotes: 10

Views: 21901

Answers (2)

meTchaikovsky
meTchaikovsky

Reputation: 7666

If you are only dealing with numpy arrays, I think slicing would be enough

Say, the shape of the loaded numpy array is (m, n) (one channel), and the target shape is (a, b). Then, the stride can be (s1, s2) = (m // a, n // b)

So the original array can be sliced by

new_array = old_array[::s1, ::s2]

EDIT

To scale up an array is also quite straight forward if you use masks for advanced slicing. For example, the shape of the original array is (m, n), and the target shape is (a, b). Then, as an example

a, b = 300, 200
m, n = 3, 4

original = np.linspace(1, 12, 12).reshape(3, 4)
canvas = np.zeros((a, b))
(s1, s2) = (a // m, b // n) # the scalar

# the two masks  
mask_x = np.concatenate([np.ones(s1) * ind for ind in range(m)])
mask_y = np.concatenate([np.ones(s2) * ind for ind in range(n)])

# make sure the residuals are taken into account
if len(mask_x) < a: mask_x = np.concatenate([mask_x, np.ones(len(mask_x) % a) * (m - 1)])
if len(mask_y) < b: mask_y = np.concatenate([mask_y, np.ones(len(mask_y) % b) * (n - 1)])
mask_x = mask_x.astype(np.int8).tolist()
mask_y = mask_y.astype(np.int8).tolist()

canvas = original[mask_x, :]
canvas = canvas[:, mask_y]

Upvotes: 1

Matt Hall
Matt Hall

Reputation: 8122

Try PIL, maybe it's fast enough for you.

import numpy as np
from PIL import Image

arr = np.load('img.npy')
img = Image.fromarray(arr)
img.resize(size=(100, 100))

Note that you have to compute the aspect ratio if you want to keep it. Or you can use Image.thumbnail(), which can take an antialias filter.

There's also scikit-image, but I suspect it's using PIL under the hood. It works on NumPy arrays:

import skimage.transform as st

st.resize(arr, (100, 100))

I guess the other option is OpenCV.

Upvotes: 13

Related Questions