python矩阵变成图片,使用python将图像转换为矩阵

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

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[:]

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])

This will yield a width x height x num_images numpy array, assuming that all of your images have the same dimensions.

However, your images will be unsorted, so you may want to do filenames.sort().

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值