简体   繁体   English

显示文件夹python中的所有图像的问题

[英]problem in showing all images from folder python

I want to show all images from a folder through python but got this error -我想通过 python 显示文件夹中的所有图像,但出现此错误 -

File "<tokenize>", line 18
    imagesList = listdir(path) IndentationError: unindent does not match any outer indentation level

code:代码:

from os import listdir
from PIL import Image as PImage

def loadImages(path):

imagesList = listdir(path)
loadedImages = []
for image in imagesList:
    img = PImage.open(path + image)
    loadedImages.append(img)

return loadedImages

path = "CATS_DOGS/train/CAT/"
 imgs = loadImages(path)

for img in imgs:
img.show()

This is simply an indentation issue, just as the error says so.这只是一个缩进问题,正如错误所说的那样。

This is how it should be:应该是这样:

from os import listdir
from PIL import Image as PImage

def loadImages(path):
   imagesList = listdir(path)
   loadedImages = []
   for image in imagesList:
      img = PImage.open(path + image)
      loadedImages.append(img)
      img.close()
   return loadedImages

path = "CATS_DOGS/train/CAT/"
imgs = loadImages(path)

for img in imgs:
   img.show()

That's because in python the syntax is to use indents (tab), instead the use of { } in other languages (like java, c# js, etc.), in order to enter an inner scope.那是因为在python ,语法是使用缩进(制表符),而不是在其他语言(如 java、c# js 等)中使用{ } ,以便进入内部作用域。

So just use indent in all your function code, which will define your code inside the function loadImages :因此,只要在所有的功能代码,它将定义的函数内部代码中使用缩进loadImages

def loadImages(path):

    imagesList = listdir(path)
    loadedImages = []
    for image in imagesList:
        img = PImage.open(path + image)
        loadedImages.append(img)

    return loadedImages

path = "CATS_DOGS/train/CAT/"
imgs = loadImages(path)

for img in imgs:
img.show()

Plus, the line imgs = loadImages(path) was with 1 space indent, which may cause the same problem again.另外,行imgs = loadImages(path)缩进了 1 个空格,这可能会再次导致相同的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM