Я играл с Tensorflow для классификации изображений. Я использовал image_retraining/retrain.py переквалифицироваться библиотекой новых начала работ по категориям и использовал его для классификации изображений с использованием label_image.py из https://github.com/llSourcell/tensorflow_image_classifier/blob/master/src/label_image.py, как показано ниже:Tensorflow Label_Image для PNG, GIF и т. Д.
import tensorflow as tf
import sys
# change this as you see fit
image_path = sys.argv[1]
# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("/root/tf_files/output_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("/root/tf_files/output_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
#predictions = sess.run(softmax_tensor,{'DecodeJpeg/contents:0': image_data})
predictions = sess.run(softmax_tensor,{'DecodePng/contents:0': image_data})
# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
print('%s (score = %.5f)' % (human_string, score))
я заметил две проблемы. Когда я перестраиваюсь с новыми категориями, он обрабатывает только изображения JPG. Я новичок в машинах, поэтому не уверен, является ли это ограничением или можно ли тренировать другие изображения с расширением, такие как PNG, GIF?
Другой, когда классифицирует изображения, вводится снова только для JPG. Я попытался изменить DecodeJpeg на DecodePng в label_image.py выше, но не смог работать. Другой способ, которым я попытался было конвертировать другие форматы в JPG перед передачей их в классификации, как:
im = Image.open('/root/Desktop/200_s.gif').convert('RGB')
im.save('/root/Desktop/test.jpg', "JPEG")
image_path1 = '/root/Desktop/test.jpg'
Есть ли другой способ сделать это? У Tensorflow есть функции для обработки других форматов изображений, отличных от JPG?
Я попытался следующие путем подачи в обработанном изображении по сравнению с JPEG, как предложено @mrry
import tensorflow as tf
import sys
import numpy as np
from PIL import Image
# change this as you see fit
image_path = sys.argv[1]
# Read in the image_data
image_data = tf.gfile.FastGFile(image_path, 'rb').read()
image = Image.open(image_path)
image_array = np.array(image)[:,:,0:3] # Select RGB channels only.
# Loads label file, strips off carriage return
label_lines = [line.rstrip() for line
in tf.gfile.GFile("/root/tf_files/output_labels.txt")]
# Unpersists graph from file
with tf.gfile.FastGFile("/root/tf_files/output_graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='')
with tf.Session() as sess:
# Feed the image_data as input to the graph and get first prediction
softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
predictions = sess.run(softmax_tensor,{'DecodeJpeg:0': image_array})
# Sort to show labels of first prediction in order of confidence
top_k = predictions[0].argsort()[-len(predictions[0]):][::-1]
for node_id in top_k:
human_string = label_lines[node_id]
score = predictions[0][node_id]
print('%s (score = %.5f)' % (human_string, score))
Он работает для изображений JPEG, но когда я использую PNG или GIF он бросает
Traceback (most recent call last):
File "label_image.py", line 17, in <module>
image_array = np.array(image)[:,:,0:3] # Select RGB channels only.
IndexError: too many indices for array
Спасибо и с уважением
О 'IndexError', сообщение об ошибке предполагает, что' image' не имеет трех измерений. Что вы получаете, если вы выполняете 'print (np.Массив (изображение) .shape) '? Можете ли вы попробовать 'np.asarray (image)' вместо этого? – mrry
@mrry Возможность сделать это сейчас. Впоследствии изображение image.convert ('RGB') и фид в массиве. Теперь можно использовать JPG, PNG и GIF. – aandroidtest