使用python将图像转换为矩阵 [英] Image to matrix using python
问题描述
我需要访问文件夹中的所有图像并将其存储在矩阵中。我能够使用matlab完成它,这里是代码:
I am required to access all images in a folder and store it in a matrix. I was able to do it using matlab and here is the code:
input_dir = 'C:\Users\Karim\Downloads\att_faces\New Folder';
image_dims = [112, 92];
filenames = dir(fullfile(input_dir, '*.pgm'));
num_images = numel(filenames);
images = [];
for n = 1:num_images
filename = fullfile(input_dir, filenames(n).name);
img = imread(filename);
img = imresize(img,image_dims);
end
但我需要使用python执行此操作,这是我的python代码:
but I am required to do it using python and here is my python code:
import Image
import os
from PIL import Image
from numpy import *
import numpy as np
#import images
dirname = "C:\\Users\\Karim\\Downloads\\att_faces\\New folder"
#get number of images and dimentions
path, dirs, files = os.walk(dirname).next()
num_images = len(files)
image_file = "C:\\Users\\Karim\\Downloads\\att_faces\\New folder\\2.pgm"
im = Image.open(image_file)
width, height = im.size
images = []
for x in xrange(1, num_images):
filename = os.listdir(dirname)[x]
img = Image.open(filename)
img = im.convert('L')
images[:, x] = img[:]
但我得到了是错误:
IOError:[Errno 2]没有这样的文件或目录:'10 .pgm'
虽然文件存在但是。
but I am getting this error: IOError: [Errno 2] No such file or directory: '10.pgm' although the file is present.
推荐答案
我不太确定你的目标是什么,但尝试更像这样的事情:
I'm not quite sure what your end goal is, but try something more like this:
import numpy as np
import Image
import glob
filenames = glob.glob('/path/to/your/files/*.pgm')
images = [Image.open(fn).convert('L') for fn in filenames]
data = np.dstack([np.array(im) for im in images])
这将产生宽度x高度x num_images numpy数组,假设您的所有图像具有相同的尺寸。
This will yield a width x height x num_images numpy array, assuming that all of your images have the same dimensions.
但是,您的图像将是未分类的,因此您可能需要执行文件名。 sort()
。
However, your images will be unsorted, so you may want to do filenames.sort()
.
此外,您可能想要或不想要3D numpy数组,但这完全取决于你的内容实际上在做。如果你只想单独操作每个框架,那么不要费心将它们堆叠成一个巨大的阵列。
Also, you may or may not want things as a 3D numpy array, but that depends entirely on what you're actually doing. If you just want to operate on each "frame" individually, then don't bother stacking them into one gigantic array.
这篇关于使用python将图像转换为矩阵的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!