label_image将截图添加到image_path

时间:2017-07-08 14:13:25

标签: python-3.x opencv tensorflow image-recognition

我需要将屏幕截图添加到网络而不是image_path

import os, sys
import cv2
import numpy as np
from PIL import ImageGrab
import tensorflow as tf

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

### take a screan shot
printscreen =  np.array(ImageGrab.grab(bbox=(0,0,800,800)))
imagescrean =  cv2.cvtColor(printscreen, cv2.COLOR_BGR2RGB)

# change this as you see fit
##image_path = sys.argv[1]  ### change path to
image_path = imagescrean    ### screan shot

# 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("retrained_labels.txt")]

# Unpersists graph from file
with tf.gfile.FastGFile("retrained_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})

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

问题在于

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

取数字并告诉我

Expected binary or unicode string, got array([[[203, 186, 168],

[203, 186, 168],

[235, 230, 224],

1 个答案:

答案 0 :(得分:0)

正如错误所说,你在这里尝试做的是传递数组而不是路径到图像。这是因为您的屏幕截图未保存,因此它还没有路径。

一个简单的解决方案是首先保存屏幕截图,然后传递该路径。

cv2.imwrite("screenshot.jpg", imagescrean)
image_path = "screenshot.jpg"

这应该可以正常工作。