繁体   English   中英

Python Tensorflow中的人脸识别系统

[英]Face Recognition system in Python Tensorflow

因此,我决定进一步研究Google Tensorflow中的MNIST教程 ,并尝试创建一个基本的人脸识别系统。

目录:

amar->包含所有目标图像

测试->包含所有带有负片的测试图像

火车->包含所有训练图像

每个目录中有60个图像文件。 我正在使用目录名称作为图像标签。

在这一点上,我能够提取图像强度,并且一切都已完成,但是出现以下错误:

I tensorflow/core/common_runtime/local_device.cc:40] Local device intra op parallelism threads: 4
I tensorflow/core/common_runtime/direct_session.cc:58] Direct session inter op parallelism threads: 4
[[0, 0, 1], [0, 0, 1]]
Traceback (most recent call last):
  File "face.py", line 82, in <module>
    model()
  File "face.py", line 74, in model
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/client/session.py", line 357, in run
    np_val = np.array(subfeed_val, dtype=subfeed_t.dtype.as_numpy_dtype)
ValueError: setting an array element with a sequence.

以下是代码:

def preprocessImages(dir):      # Grescaling the images
    from os import listdir
    from os.path import isfile, join
    import Image    
    path = dir
    onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
    for files in onlyfiles:
        img = Image.open(str(path+files)).convert('L')
        img.save(str(path+files))

def extractImages(path):        # Extracting image pixel intensities in an array
    images = []
    from os import listdir
    from os.path import isfile, join
    import Image
    onlyfiles = [f for f in listdir(path) if isfile(join(path, f))]
    for image in onlyfiles:
        img = Image.open(path+image)
        pixVal = list(img.getdata())
        images.append(pixVal)
    return images

def extractLabels(target):      # Extracting labels or directories accordingly 
    res = []
    path = './'
    from os import listdir
    from os.path import isfile, join
    import Image    
    onlyfiles = [f for f in listdir(path) if not isfile(join(path, f))]
    for i in onlyfiles:
        if i == target:
            res.append(1)
        else:
            res.append(0)
    return res
dirs = ['train','test','amar']  # put some directories here
labels = []
images = []

for di in dirs:
    labels.append(extractLabels(di))        
    images.append(extractImages(('./'+di+'/')))

def batch(no):          # Function to select a batch of elements from both the arrays
    import random
    import numpy as np
    global labels
    global images
    lab = []
    img = []
    for i in range(no):
        lab.append(random.choice(labels))
    for i in range(no):
        img.append(random.choice(images))
    return img,lab

def model():
    import tensorflow as tf
    x = tf.placeholder(tf.float32, [None,409600])       # The images of 240x240 = 409600 pixels
    W = tf.Variable(tf.zeros([409600,3]))           # The weights for each image 
    b = tf.Variable(tf.zeros([3]))              # The labels of the images containing the real numbers
    y = tf.nn.softmax(tf.matmul(x, W) + b)          # The predicted y viz. y = softmax(W*x + b)
    y_ = tf.placeholder(tf.float32, [None, 3])      # The real y that will be checked against the prediction
    cross_entropy = -tf.reduce_sum(y_*tf.log(y))        # The entropy error b/w the y and y_
    train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)    # The method to optimize error at each training step
    init = tf.initialize_all_variables()            # initializing all variables
    sess = tf.Session()
    sess.run(init)

    # Training for our model
    for i in range(1000):                   
      batch_xs, batch_ys = batch(2)
      print batch_ys
      sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})

    correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))      # Checking for the prediction
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))     # Accuracy of the prediction
    accuracy = sess.run(accuracy, feed_dict={x: extractImages('./test/'), y_: extractLabels('test')})*100   # Normalizing it in terms of percentage
    print "The accuracy of the model was",accuracy," %"
    print type(mnist)

model()

batch_xs和batch_ys(通常是feed_dict的输入)应该是numpy数组,而不是列表。

在您的批处理功能中,您将返回图像,标签,并且两者都是列表类型。 我的建议是,在返回图像之前将其转换为np.array。 像这样的东西

def batch(no):
     do the batch calculation and prepare the img,label set
     # now before returning convert then to np array
     img = np.array(img)
     return img, label

我在代码中尝试了批处理功能,这就是解决错误的方法。

希望这能解决您的错误。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM