我正在尝试在 python 中打开一组图像,但我有点困惑我应该如何做到这一点。我知道如何处理一张图像,但不知道如何处理数百张图像。
我有一个文件夹,里面有几百张 .jpg 图像。我想将它们加载到 python 程序中以对它们进行机器学习。我怎样才能正确地做到这一点?
我还没有任何代码,因为我已经在为此苦苦挣扎。
但是我的伪代码想法是
dataset = load(images)
do some manipulations on it
我以前是如何做到的:
from sklearn.svm import LinearSVC
from numpy import genfromtxt,savetxt
load = lambda x: genfromtxt(open(x,"r"),delimiter = ",",dtype = "f8")[1:]
dataset = load("train.csv")
train = [x[1:] for x in dataset]
target = [x[0] for x in dataset]
test = load("test.csv")
linear = LinearSVC()
linear.fit(train,target)
savetxt("digit2.csv",linear.predict(test),delimiter = ",", fmt = "%d")
由于格式的原因,效果很好。所有数据都在一个文件中。
最佳答案
如果您想单独处理每个图像(假设您使用的是 PIL 或 Pillow),请按顺序执行此操作:
import os
from glob import glob
try:
# PIL
import Image
except ImportError:
# Pillow
from PIL import Image
def process_image(img_path):
print "Processing image: %s" % img_path
# Open the image
img = Image.open(img_path)
# Do your processing here
print img.info
# Not strictly necessary, but let's be explicit:
# Close the image
del img
images_dir = "/home/user/images"
if __name__ == "__main__":
# List all JPEG files in your directory
images_list = glob(os.path.join(images_dir, "*.jpg"))
for img_filename in images_list:
img_path = os.path.join(images_dir, img_filename)
process_image(img_path)
关于python - 如何在Python中正确加载一组图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19346731/