Python 路径有问题
好吧,我需要,用我导师自己的话来说: -读入images目录中的所有图像 -为每个图像创建直方图。直方图函数不能使用PIL函数Image.historgam 到目前为止,我已经掌握了以下基本代码:Python 路径有问题,python,path,Python,Path,好吧,我需要,用我导师自己的话来说: -读入images目录中的所有图像 -为每个图像创建直方图。直方图函数不能使用PIL函数Image.historgam 到目前为止,我已经掌握了以下基本代码: from os import listdir from PIL import Image as PImage def loadImages(path): imagesList = listdir(path) loadedImages = [] for image in ima
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()
问题是路径=/bit。我不知道如何正确地使用它,以便程序从我的桌面(或者如果你推荐的话,我可以放在任何地方)读取一个名为“图像”的文件
请尽快回复,在我这么做之前,我无法完成我的任务 您应该使用
os.path
来处理文件路径
import os
for filename in filelist:
full_path = os.path.join(path, filename)
您还应该考虑<代码> OS.Listdir 还包括其结果中的目录。此外,在您定义
path
的代码中可能存在错误,看起来您缺少结束引号。使用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()
这里有一个解决方案
- 提示用户输入要扫描的路径
- 使用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()
运行代码时,您没有提到出现了什么问题。这是找出问题所在的重要部分。顺便说一句,print是你的朋友。在for循环中执行
print(path+image)
以查看您得到了什么。“问题是路径=/bit。我不知道如何正确地拼写它,以便程序从我的桌面读取名为“images”的文件(或者如果您推荐,我可以将其放在任何其他地方)。”您的代码读取目录中的所有图像,但您说要读取一个名为“图像”的文件。令人困惑我的问题是我不知道我的路径或文件列表是什么。这不起作用。它导致了有关文字的错误。如果不知道文件在哪里,您打算如何打开这些文件<代码>路径应该类似于“/path/to/mypics”
,文件列表
应该是os.listdir(path)
我不能使用PIL作为直方图,我仍然不知道如何从我学校的timmy驱动器进行路径设置。转到包含照片的文件夹,右键单击其中一张照片,单击属性,看看什么location
istank you Uriel!我会试试的!