Serquet Serquet - 5 months ago 47
Python Question

Python, resize images that are in a folder

I'm new in this community and with Python too. I'm trying to do image classification with Python but I have some problems in loading data. I have 16'000 images in a folder and they have different number of pixel. I want to resize them in a square shape and, after, I want to convert image in matrix but I can't! This is my code:

import cv2
import PIL
from PIL import Image
import numpy as np
import glob

food_imgs = np.zeros(300*300*3)

for i, img in enumerate(glob.glob("Downloads/Food-11/training/*.jpg")):
if i == 5:
fo =
fo = fo.resize((300, 300))
food_imgs = np.c_[food_imgs, cv2.imread(fo).flatten()]

The error is:

TypeError Traceback (most recent call last)
<ipython-input-41-b5adecbdc8f9> in <module>()
6 fo =
7 fo = fo.resize((300, 300), PIL.Image.ANTIALIAS)
----> 8 food_imgs = np.c_[food_imgs, cv2.imread(fo).flatten()]

TypeError: expected string or Unicode object, Image found

Answer Source
> #!/usr/bin/python from PIL import Image import os, sys
> path = "/root/Desktop/python/images/" dirs = os.listdir( path )
> #Don't froget to change your path!
> def resize():
>     for item in dirs: #Iterates through each picture
>         if os.path.isfile(path+item): 
>             im =
>             f, e = os.path.splitext(path+item)
>             imResize = im.resize((200,200), Image.ANTIALIAS)
>    + ' resized.jpg', 'JPEG', quality=90)
> resize()

Found HERE