tf.gfile.FastGFile(imagePath,' rb')。read()

时间:2018-05-04 05:59:40

标签: python tensorflow

我尝试以inception_v3为例。 我使用底层代码,但我想放置图像本身,而不是图像路径。有办法吗?

def run_inference_on_image():
    answer = None

    if not tf.gfile.Exists(imagePath):
        tf.logging.fatal('File does not exist %s', imagePath)
        return answer

    image_data = tf.gfile.FastGFile(imagePath, 'rb').read()

    create_graph()

    with tf.Session() as sess:

        softmax_tensor = sess.graph.get_tensor_by_name('final_result:0')
        predictions = sess.run(softmax_tensor,
                           {'DecodeJpeg/contents:0': image_data})
        predictions = np.squeeze(predictions)

        top_k = predictions.argsort()[-2:][::-1]  
        f = open(labelsFullPath, 'rb')
        lines = f.readlines()
        labels = [str(w).replace("\n", "") for w in lines]
        for node_id in top_k:
            human_string = labels[node_id]
            score = predictions[node_id]
            print('%s (score = %.5f)' % (human_string, score))

        answer = labels[top_k[0]]
    return answer

图像是我想要归类为学习PB文件的图像。

1 个答案:

答案 0 :(得分:4)

image_data是代码中的实际图像字节。它们正在sess.run()函数中使用。下面的代码行将图像字节作为字符串返回。

  

tf.gfile.FastGFile(imagePath,' rb')。read()

因此,您所要做的就是将string of image bytes传递给sess.run(),这可以通过多种方式完成: -

# method 1
import cv2
img_str = cv2.imencode('.jpg', img)[1].tostring()

# method 2
from scipy.ndimage import imread
imgbytes = imread(img_path)
img_str = imgbytes.tostring()

检查什么对你有用。