【问题标题】:Python, resize images that are in a folder [duplicate]Python,调整文件夹中的图像大小[重复]
【发布时间】:2017-10-10 22:30:40
【问题描述】:

我是这个社区的新手,也是 Python 的新手。我正在尝试使用 Python 进行图像分类,但在加载数据时遇到了一些问题。我在一个文件夹中有 16'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

【问题讨论】:

  • cv2.imread 需要一个文件名作为参数

标签: python image classification python-imaging-library


【解决方案1】:
> #!/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

【讨论】:

  • 谢谢!效果很好!
  • 太棒了,您可能会遇到一些问题。它有效,但这是一种粗略的做法,因为您将它用于 np.如果您还有其他需要,请告诉我。
  • 请将问题标记为重复,而不是复制和粘贴现有答案。
猜你喜欢
  • 1970-01-01
  • 2014-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-20
  • 1970-01-01
相关资源
最近更新 更多