example2 - person height.py
Go to the documentation of this file.
1 import pyrealsense2 as rs
2 import numpy as np
3 import cv2
4 import tensorflow as tf
5 
6 W = 848
7 H = 480
8 
9 # Configure depth and color streams
10 pipeline = rs.pipeline()
11 config = rs.config()
12 config.enable_stream(rs.stream.depth, W, H, rs.format.z16, 30)
13 config.enable_stream(rs.stream.color, W, H, rs.format.bgr8, 30)
14 
15 
16 print("[INFO] start streaming...")
17 pipeline.start(config)
18 
19 aligned_stream = rs.align(rs.stream.color) # alignment between color and depth
20 point_cloud = rs.pointcloud()
21 
22 print("[INFO] loading model...")
23 PATH_TO_CKPT = r"frozen_inference_graph.pb"
24 # download model from: https://github.com/opencv/opencv/wiki/TensorFlow-Object-Detection-API#run-network-in-opencv
25 
26 # Load the Tensorflow model into memory.
27 detection_graph = tf.Graph()
28 with detection_graph.as_default():
29  od_graph_def = tf.compat.v1.GraphDef()
30  with tf.compat.v1.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
31  serialized_graph = fid.read()
32  od_graph_def.ParseFromString(serialized_graph)
33  tf.compat.v1.import_graph_def(od_graph_def, name='')
34  sess = tf.compat.v1.Session(graph=detection_graph)
35 
36 # Input tensor is the image
37 image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')
38 # Output tensors are the detection boxes, scores, and classes
39 # Each box represents a part of the image where a particular object was detected
40 detection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0')
41 # Each score represents level of confidence for each of the objects.
42 # The score is shown on the result image, together with the class label.
43 detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')
44 detection_classes = detection_graph.get_tensor_by_name('detection_classes:0')
45 # Number of objects detected
46 num_detections = detection_graph.get_tensor_by_name('num_detections:0')
47 # code source of tensorflow model loading: https://www.geeksforgeeks.org/ml-training-image-classifier-using-tensorflow-object-detection-api/
48 
49 while True:
50  frames = pipeline.wait_for_frames()
51  frames = aligned_stream.process(frames)
52  depth_frame = frames.get_depth_frame()
53  color_frame = frames.get_color_frame()
54  points = point_cloud.calculate(depth_frame)
55  verts = np.asanyarray(points.get_vertices()).view(np.float32).reshape(-1, W, 3) # xyz
56 
57  # Convert images to numpy arrays
58  color_image = np.asanyarray(color_frame.get_data())
59  scaled_size = (int(W), int(H))
60  # expand image dimensions to have shape: [1, None, None, 3]
61  # i.e. a single-column array, where each item in the column has the pixel RGB value
62  image_expanded = np.expand_dims(color_image, axis=0)
63  # Perform the actual detection by running the model with the image as input
64  (boxes, scores, classes, num) = sess.run([detection_boxes, detection_scores, detection_classes, num_detections],
65  feed_dict={image_tensor: image_expanded})
66 
67  boxes = np.squeeze(boxes)
68  classes = np.squeeze(classes).astype(np.int32)
69  scores = np.squeeze(scores)
70 
71  print("[INFO] drawing bounding box on detected objects...")
72  print("[INFO] each detected object has a unique color")
73 
74  for idx in range(int(num)):
75  class_ = classes[idx]
76  score = scores[idx]
77  box = boxes[idx]
78  print(" [DEBUG] class : ", class_, "idx : ", idx, "num : ", num)
79 
80  if score > 0.8 and class_ == 1: # 1 for human
81  left = box[1] * W
82  top = box[0] * H
83  right = box[3] * W
84  bottom = box[2] * H
85 
86  width = right - left
87  height = bottom - top
88  bbox = (int(left), int(top), int(width), int(height))
89  p1 = (int(bbox[0]), int(bbox[1]))
90  p2 = (int(bbox[0] + bbox[2]), int(bbox[1] + bbox[3]))
91  # draw box
92  cv2.rectangle(color_image, p1, p2, (255,0,0), 2, 1)
93 
94  # x,y,z of bounding box
95  obj_points = verts[int(bbox[1]):int(bbox[1] + bbox[3]), int(bbox[0]):int(bbox[0] + bbox[2])].reshape(-1, 3)
96  zs = obj_points[:, 2]
97 
98  z = np.median(zs)
99 
100  ys = obj_points[:, 1]
101  ys = np.delete(ys, np.where(
102  (zs < z - 1) | (zs > z + 1))) # take only y for close z to prevent including background
103 
104  my = np.amin(ys, initial=1)
105  My = np.amax(ys, initial=-1)
106 
107  height = (My - my) # add next to rectangle print of height using cv library
108  height = float("{:.2f}".format(height))
109  print("[INFO] object height is: ", height, "[m]")
110  height_txt = str(height) + "[m]"
111 
112  # Write some Text
113  font = cv2.FONT_HERSHEY_SIMPLEX
114  bottomLeftCornerOfText = (p1[0], p1[1] + 20)
115  fontScale = 1
116  fontColor = (255, 255, 255)
117  lineType = 2
118  cv2.putText(color_image, height_txt,
119  bottomLeftCornerOfText,
120  font,
121  fontScale,
122  fontColor,
123  lineType)
124 
125  # Show images
126  cv2.namedWindow('RealSense', cv2.WINDOW_AUTOSIZE)
127  cv2.imshow('RealSense', color_image)
128  cv2.waitKey(1)
129 
130 # Stop streaming
131 pipeline.stop()
void reshape(GLFWwindow *window, int w, int h)
Definition: boing.c:215
static std::string print(const transformation &tf)


librealsense2
Author(s): Sergey Dorodnicov , Doron Hirshberg , Mark Horn , Reagan Lopez , Itay Carpis
autogenerated on Mon May 3 2021 02:47:14