在jupyter里用python处理图像并提取图像特征做人脸识别实验
华工小软 2018-10-23 07:48:23 本人python小白一枚,学院突然要求用python做机器学习基于Adaboost算法的人脸识别实验。。猝不及防呀。。
写了一会儿代码之后发现,自己的程序调用老师提供feature.py的类方法时会报错index error,看了半天不知道哪里出错,希望能有高手指点。
顺便问一下,如何用pickle库中的dump()函数将特征数据存在缓存中,稍后再用load()读取?
报错信息:
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
<ipython-input-16-7de3db667e50> in <module>()
52 for k in range(data_size - 1):
53 npd = NPDFeature(img_set[k])
---> 54 npd.extract()
<ipython-input-16-7de3db667e50> in extract(self)
32 for i in range(self.n_pixels - 1):
33 for j in range(i + 1, self.n_pixels, 1):
---> 34 self.features[count] = NPDFeature.__NPD_table__[self.image[i]][self.image[j]]
35 count += 1
36 return self.features
IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
代码:
from skimage import data_dir,transform,color
import numpy
import cv2
import skimage.io as io
import matplotlib.pyplot as plt
def convert_gray(f):
rgb=io.imread(f) # read RGB image
gray=color.rgb2gray(rgb) # convert RGB images to Gray images
dst=transform.resize(gray,(24,24)) # resize
return dst
path='/Users/jzh/Desktop/ML2018-lab-03-master/datasets/original/face/*.jpg:/Users/jzh/Desktop/ML2018-lab-03-master/datasets/original/nonface/*.jpg' # this is my images' path
img_set = io.ImageCollection(path,load_func=convert_gray) # load images and convert them
#io.imshow(img_set[20])
# %load feature.py
import numpy
data_size = 1000 # there are totally 1000 images
class NPDFeature():
"""It is a tool class to extract the NPD features.
Attributes:
image: A two-dimension ndarray indicating grayscale image.
n_pixels: An integer indicating the number of image total pixels.
features: A one-dimension ndarray to store the extracted NPD features.
"""
__NPD_table__ = None
def __init__(self, image):
'''Initialize NPDFeature class with an image.'''
if NPDFeature.__NPD_table__ is None:
NPDFeature.__NPD_table__ = NPDFeature.__calculate_NPD_table()
assert isinstance(image, numpy.ndarray)
self.image = image.ravel()
self.n_pixels = image.size
self.features = numpy.empty(shape=self.n_pixels * (self.n_pixels - 1) // 2, dtype=float)
def extract(self):
'''Extract features from given image.
Returns:
A one-dimension ndarray to store the extracted NPD features.
'''
count = 0
for i in range(self.n_pixels - 1):
for j in range(i + 1, self.n_pixels, 1):
self.features[count] = NPDFeature.__NPD_table__[self.image[i]][self.image[j]] #报错
count += 1
return self.features
@staticmethod
def __calculate_NPD_table():
'''Calculate all situations table to accelerate feature extracting.'''
print("Calculating the NPD table...")
table = numpy.empty(shape=(1 << 8, 1 << 8), dtype=float)
for i in range(1 << 8):
for j in range(1 << 8):
if i == 0 and j == 0:
table[i][j] = 0
else:
table[i][j] = (i - j) / (i + j)
return table
# extract features
for k in range(data_size - 1):
npd = NPDFeature(img_set[k])
npd.extract() #extract处报错