我通过遵循在线人体检测教程来进行了tensorflow python scipt。此实现将OpenCV和Tensorflow结合在一起以检测人并在人所在的屏幕上绘图。
我的问题是我现在在python中工作,为了将模型加载到TensorflowSharp以在Unity中使用,我需要将模型保存为.bytes格式。
很明显,我必须使用freeze_graph函数,这是我认为必须在设置Python环境中进行一些固定的地方。
在我的新代码段中,此行之后:
freeze_graph.freeze_graph(input_graph = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb',
input_binary = True,
input_checkpoint = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt',
output_node_names = node_names,
output_graph = 'G:/TensorHumanDetect/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph_test.bytes' ,
clear_devices = True, initializer_nodes = "",input_saver = "",
restore_op_name = "save/restore_all", filename_tensor_name = "save/image_tensor:0")
我收到此错误:
发生异常:AttributeError'NoneType'对象没有 属性“写入”文件“ G:\ tensorhumandetect \ test.py”,第40行,在 restore_op_name =“ save / restore_all”,filename_tensor_name =“ save / image_tensor:0”)
代码:
import tensorflow as tf
# freeze_graph "screenshots" the graph from tensorflow.python.tools import freeze_graph
# optimize_for_inference lib optimizes this frozen graph from tensorflow.python.tools import optimize_for_inference_lib
# os and os.path are used to create the output file where we save our frozen graphs import os import os.path as path
path_to_ckpt = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb' detection_graph = tf.Graph() with detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(path_to_ckpt, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
default_graph = detection_graph.as_default() sess = tf.Session(graph=detection_graph)
# Definite input and output Tensors for detection_graph image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected. detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label. detection_scores = detection_graph.get_tensor_by_name('detection_scores:0') detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') num_detections = detection_graph.get_tensor_by_name('num_detections:0')
node_names = [node.name for node in tf.get_default_graph().as_graph_def().node] freeze_graph.freeze_graph(input_graph = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb',
input_binary = True,
input_checkpoint = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt',
output_node_names = node_names,
output_graph = 'G:/TensorHumanDetect/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph_test.bytes' ,
clear_devices = True, initializer_nodes = "",input_saver = "",
restore_op_name = "save/restore_all", filename_tensor_name = "save/image_tensor:0")
人员检测的工作示例:
import numpy as np
import tensorflow as tf
from tensorflow.python.tools import freeze_graph
import cv2
import time
import json
import io
import sys
import os
class DetectorAPI:
def __init__(self, path_to_ckpt):
self.path_to_ckpt = path_to_ckpt
self.detection_graph = tf.Graph()
with self.detection_graph.as_default():
od_graph_def = tf.GraphDef()
with tf.gfile.GFile(self.path_to_ckpt, 'rb') as fid:
serialized_graph = fid.read()
od_graph_def.ParseFromString(serialized_graph)
tf.import_graph_def(od_graph_def, name='')
self.default_graph = self.detection_graph.as_default()
self.sess = tf.Session(graph=self.detection_graph)
# Definite input and output Tensors for detection_graph
self.image_tensor = self.detection_graph.get_tensor_by_name('image_tensor:0')
# Each box represents a part of the image where a particular object was detected.
self.detection_boxes = self.detection_graph.get_tensor_by_name('detection_boxes:0')
# Each score represent how level of confidence for each of the objects.
# Score is shown on the result image, together with the class label.
self.detection_scores = self.detection_graph.get_tensor_by_name('detection_scores:0')
self.detection_classes = self.detection_graph.get_tensor_by_name('detection_classes:0')
self.num_detections = self.detection_graph.get_tensor_by_name('num_detections:0')
def processFrame(self, image):
# Expand dimensions since the trained_model expects images to have shape: [1, None, None, 3]
image_np_expanded = np.expand_dims(image, axis=0)
# Actual detection.
#start_time = time.time()
(boxes, scores, classes, num) = self.sess.run(
[self.detection_boxes, self.detection_scores, self.detection_classes, self.num_detections],
feed_dict={self.image_tensor: image_np_expanded})
#end_time = time.time()
#print("Elapsed Time:", end_time-start_time)
im_height, im_width,_ = image.shape
boxes_list = [None for i in range(boxes.shape[1])]
for i in range(boxes.shape[1]):
boxes_list[i] = (int(boxes[0,i,0] * im_height),
int(boxes[0,i,1]*im_width),
int(boxes[0,i,2] * im_height),
int(boxes[0,i,3]*im_width))
return boxes_list, scores[0].tolist(), [int(x) for x in classes[0].tolist()], int(num[0])
def close(self):
self.sess.close()
self.default_graph.close()
if __name__ == "__main__":
model_path = 'G:/TensorflowHumanDetectino/faster_rcnn_inception_v2_coco_2018_01_28/frozen_inference_graph.pb'
odapi = DetectorAPI(path_to_ckpt=model_path)
threshold = 0.7
#cap = cv2.VideoCapture('G:/TensorflowHumanDetectino/TownCentreXVID.avi')
cap = cv2.VideoCapture(0)
while True:
r, img = cap.read()
img = cv2.resize(img, (1280, 720))
boxes, scores, classes , num = odapi.processFrame(img)
myfile = open('HumanLocations.txt','w')
# Visualization of the results of a detection.
for i in range(len(boxes)):
# Class 1 represents human
if classes[i] == 1 and scores[i] > threshold:
box = boxes[i]
cv2.rectangle(img,(box[1],box[0]),(box[3],box[2]),(255,0,0),2)
myfile.write(str(boxes[i][0])+','+str(boxes[i][1])+','+str(boxes[i][2])+','+str(boxes[i][3])+'|')
myfile.close()
cv2.imshow("preview", img)
key = cv2.waitKey(1)
if key & 0xFF == ord('q'):
break
另一个奇怪的信息可能是不正确的环境设置的线索,是当我尝试打印任何值(甚至是纯字符串)时,都会出现此错误:
发生异常:AttributeError'NoneType'对象没有 属性“写入”文件“ G:\ tensorhumandetect \ test.py”,第11行 打印('测试!')
这基本上与我获得的Frozen_graph行相同。我是python的新手,更多是c#的人,对我们的帮助将不胜感激。 我正在使用Python 3.6.6,并使用anaconda安装了模块,并在Visual Studio Code中运行我的项目。