Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resizing image with cv2

I'm trying resize images retrieved from cifar10 in the original 32x32 to 96x96 for use with MobileNetV2, howevery I'm running into this error. Tried a variety of solutions but nothing seems to work.

My code:

for a in range(len(train_images)):
    train_images[a] = cv2.resize(train_images[a], dsize=(minSize, minSize), interpolation=cv2.INTER_CUBIC)

Error I'm getting:

----> 8     train_images[a] = cv2.resize(train_images[a], dsize=(minSize, minSize), interpolation=cv2.INTER_CUBIC)
ValueError: could not broadcast input array from shape (96,96,3) into shape (32,32,3)
like image 519
Clement Ong Avatar asked Feb 16 '26 04:02

Clement Ong


2 Answers

This is simply because you are reading the 32x32 image from train_images and trying to save the reshaped image (96x96) in the same array which is impossible! Try something like:

train_images_reshaped = np.array((num_images, 96, 96, 3))
for a in range(len(train_images)):
    train_images_reshaped[a] = cv2.resize(train_images[a], dsize=(minSize, minSize), interpolation=cv2.INTER_CUBIC)
like image 138
Ary Avatar answered Feb 17 '26 18:02

Ary


Sometimes you have to convert the image from RGB to grayscale. If that is the problem, the only thing you should do is gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY), resize the image and then again resized_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2RGB)

I have never run into this error but if the first option doesn't work, you can try and resize image with pillow like this:

from PIL import Image

im = Image.fromarray(cv2_image)
nx, ny = im.size
im2 = im.resize((nx*2, ny*2), Image.LANCZOS)
cv2_image = cv2.cvtColor(numpy.array(im2), cv2.COLOR_RGB2BGR)

You can make this into a function and call it in the list comprehension. I hope this solves your problem :)

like image 42
Novak Avatar answered Feb 17 '26 16:02

Novak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!