Python,调整文件夹中的图像大小

时间:2017-05-11 18:56:53

标签: python image classification python-imaging-library

我是这个社区的新人,也是Python的新人。我试图用Python进行图像分类,但是我在加载数据时遇到了一些问题。我在一个文件夹中有16&000,000个图像,它们具有不同的像素数。我希望将它们调整为正方形,之后,我想将矩阵转换成图像,但我不能!这是我的代码:

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:
        break
fo = Image.open(img)
fo = fo.resize((300, 300))
food_imgs = np.c_[food_imgs, cv2.imread(fo).flatten()]

错误是:

TypeError                                 Traceback (most recent call last)
<ipython-input-41-b5adecbdc8f9> in <module>()
      6     fo = Image.open(img)
      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

1 个答案:

答案 0 :(得分:0)

> #!/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 = Image.open(path+item)
>             f, e = os.path.splitext(path+item)
>             imResize = im.resize((200,200), Image.ANTIALIAS)
>             imResize.save(f + ' resized.jpg', 'JPEG', quality=90)
> 
> resize()

找到HERE