【问题标题】:Having trouble with paths路径有问题
【发布时间】:2016-10-26 15:19:36
【问题描述】:

好的,所以我需要,用我的导师自己的话来说: - 读入图像目录中的所有图像 - 为每个图像创建一个直方图。您的直方图函数不能使用 PIL 函数 Image.historgam。

到目前为止,我已经有了这个基本代码:

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 = "/

imgs = loadImages(path)

for img in imgs:
    img.show()

问题是路径 = / 位。我不知道如何正确地表达它,以便程序从我的桌面(或者如果你推荐的话,我可以把它放在其他任何地方)读取一个名为“图像”的文件。

请尽快回复,在我这样做之前,我的作业无法进行。

【问题讨论】:

  • 您在运行代码时没有提及出现了什么问题。这是找出问题所在的重要部分。顺便说一句,打印是你的朋友。在你的 for 循环中执行 print(path+image) 看看你得到了什么。
  • “问题是路径 = / 位。我不知道如何正确地用词,以便程序从我的桌面(或我可以放置的任何其他地方)读取一个名为“图像”的文件如果你推荐)。”
  • 您的代码读取了一个目录中的所有图像,但您说您想读取一个名为“images”的文件。令人困惑!

标签: python path


【解决方案1】:

您应该使用os.path 处理文件路径。

import os

for filename in filelist:
    full_path = os.path.join(path, filename)

您还应该考虑os.listdir 在其结果中还包括目录。此外,您定义 path 的代码中可能存在错误,您似乎缺少结束引号。

【讨论】:

  • 我的问题是我不知道我的路径或文件列表是什么。这不起作用。它导致了有关文字的错误。
  • 如果您不知道文件在哪里,您打算如何打开它们? path 应该是 "/path/to/mypics"filelist 应该是 os.listdir(path)
【解决方案2】:

使用os.path.join(path, filename)创建文件路径:

import os
import os.path
from PIL import *

def loadImages(path):
    return [PImage.open(os.path.join(path, image)) for image in os.listdir(path)]

for img in loadImages('/'):
    img.show()

【讨论】:

  • 我无法使用 PIL 作为直方图,而且我仍然不知道如何从学校的 timmy drive 找到路径。
  • 到有照片的文件夹,右击其中一张照片,点击properties,看看location是什么
  • 谢谢乌列尔!我会试试的!
【解决方案3】:

这是一个解决方案

  • 提示用户扫描路径
  • 使用 os.path.join 构建文件名
  • 过滤掉子目录名称
  • 捕获 PIL 错误

我认为它涵盖了最初的要求

import os
from PIL import Image as PImage

def loadImages(path):
    # paths to files in directory with non-files filtered out
    images = filter(os.path.isfile, (os.path.join(path, name) 
        for name in os.listdir(path)))
    loadedImages = []
    for image in images:
        try:
            loadedImages.append(PImage.open(image))
            print("{} is an image file".format(image))
        except OSError:
            # exception raised when PIL decides this is not an image file
            print("{} is not an image file".format(image))
    return loadedImages

while True:
    path = input("Input image path: ")
    # expand env vars and home directory tilda
    path = os.path.expanduser(os.path.expandvars(path))
    # check for bad input
    if os.path.isdir(path):
        break
    print("Not a directory. Try again.")

imgs = loadImages(path)

for img in imgs:
    img.show()

【讨论】:

    猜你喜欢
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 2017-10-02
    • 2012-02-17
    • 2011-12-27
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多