|
| 1 | +# Copyright 2021 The TensorFlow Authors. All Rights Reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | +"""Main script to run image segmentation.""" |
| 15 | + |
| 16 | +import argparse |
| 17 | +import sys |
| 18 | +import time |
| 19 | +from typing import List |
| 20 | + |
| 21 | +import cv2 |
| 22 | +from image_segmenter import ColoredLabel |
| 23 | +from image_segmenter import ImageSegmenter |
| 24 | +from image_segmenter import ImageSegmenterOptions |
| 25 | +import numpy as np |
| 26 | +import utils |
| 27 | + |
| 28 | +# Visualization parameters |
| 29 | +_FPS_AVERAGE_FRAME_COUNT = 10 |
| 30 | +_FPS_LEFT_MARGIN = 24 # pixels |
| 31 | +_LEGEND_TEXT_COLOR = (0, 0, 255) # red |
| 32 | +_LEGEND_BACKGROUND_COLOR = (255, 255, 255) # white |
| 33 | +_LEGEND_FONT_SIZE = 1 |
| 34 | +_LEGEND_FONT_THICKNESS = 1 |
| 35 | +_LEGEND_ROW_SIZE = 20 # pixels |
| 36 | +_LEGEND_RECT_SIZE = 16 # pixels |
| 37 | +_LABEL_MARGIN = 10 |
| 38 | +_OVERLAY_ALPHA = 0.5 |
| 39 | +_PADDING_WIDTH_FOR_LEGEND = 150 # pixels |
| 40 | + |
| 41 | + |
| 42 | +def run(model: str, display_mode: str, num_threads: int, enable_edgetpu: bool, |
| 43 | + camera_id: int, width: int, height: int) -> None: |
| 44 | + """Continuously run inference on images acquired from the camera. |
| 45 | +
|
| 46 | + Args: |
| 47 | + model: Name of the TFLite image segmentation model. |
| 48 | + display_mode: Name of mode to display image segmentation. |
| 49 | + num_threads: Number of CPU threads to run the model. |
| 50 | + enable_edgetpu: Whether to run the model on EdgeTPU. |
| 51 | + camera_id: The camera id to be passed to OpenCV. |
| 52 | + width: The width of the frame captured from the camera. |
| 53 | + height: The height of the frame captured from the camera. |
| 54 | + """ |
| 55 | + |
| 56 | + # Initialize the image segmentation model. |
| 57 | + options = ImageSegmenterOptions( |
| 58 | + num_threads=num_threads, enable_edgetpu=enable_edgetpu) |
| 59 | + segmenter = ImageSegmenter(model_path=model, options=options) |
| 60 | + |
| 61 | + # Variables to calculate FPS |
| 62 | + counter, fps = 0, 0 |
| 63 | + start_time = time.time() |
| 64 | + |
| 65 | + # Start capturing video input from the camera |
| 66 | + cap = cv2.VideoCapture(camera_id) |
| 67 | + cap.set(cv2.CAP_PROP_FRAME_WIDTH, width) |
| 68 | + cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height) |
| 69 | + |
| 70 | + # Continuously capture images from the camera and run inference. |
| 71 | + while cap.isOpened(): |
| 72 | + success, image = cap.read() |
| 73 | + if not success: |
| 74 | + sys.exit( |
| 75 | + 'ERROR: Unable to read from webcam. Please verify your webcam settings.' |
| 76 | + ) |
| 77 | + |
| 78 | + counter += 1 |
| 79 | + image = cv2.flip(image, 1) |
| 80 | + |
| 81 | + # Segment with each frame from camera. |
| 82 | + segmentation_result = segmenter.segment(image) |
| 83 | + |
| 84 | + # Convert the segmentation result into an image. |
| 85 | + seg_map_img, found_colored_labels = utils.segmentation_map_to_image( |
| 86 | + segmentation_result) |
| 87 | + |
| 88 | + # Resize the segmentation mask to be the same shape as input image. |
| 89 | + seg_map_img = cv2.resize( |
| 90 | + seg_map_img, |
| 91 | + dsize=(image.shape[1], image.shape[0]), |
| 92 | + interpolation=cv2.INTER_NEAREST) |
| 93 | + |
| 94 | + # Visualize segmentation result on image. |
| 95 | + overlay = visualize(image, seg_map_img, display_mode, fps, |
| 96 | + found_colored_labels) |
| 97 | + |
| 98 | + # Calculate the FPS |
| 99 | + if counter % _FPS_AVERAGE_FRAME_COUNT == 0: |
| 100 | + end_time = time.time() |
| 101 | + fps = _FPS_AVERAGE_FRAME_COUNT / (end_time - start_time) |
| 102 | + start_time = time.time() |
| 103 | + |
| 104 | + # Stop the program if the ESC key is pressed. |
| 105 | + if cv2.waitKey(1) == 27: |
| 106 | + break |
| 107 | + cv2.imshow('image_segmentation', overlay) |
| 108 | + |
| 109 | + cap.release() |
| 110 | + cv2.destroyAllWindows() |
| 111 | + |
| 112 | + |
| 113 | +def visualize(input_image: np.ndarray, segmentation_map_image: np.ndarray, |
| 114 | + display_mode: str, fps: float, |
| 115 | + colored_labels: List[ColoredLabel]) -> np.ndarray: |
| 116 | + """Visualize segmentation result on image. |
| 117 | +
|
| 118 | + Args: |
| 119 | + input_image: The [height, width, 3] RGB input image. |
| 120 | + segmentation_map_image: The [height, width, 3] RGB segmentation map image. |
| 121 | + display_mode: How the segmentation map should be shown. 'overlay' or |
| 122 | + 'side-by-side'. |
| 123 | + fps: Value of fps. |
| 124 | + colored_labels: List of colored labels found in the segmentation result. |
| 125 | +
|
| 126 | + Returns: |
| 127 | + Input image overlaid with segmentation result. |
| 128 | + """ |
| 129 | + # Show the input image and the segmentation map image. |
| 130 | + if display_mode == 'overlay': |
| 131 | + # Overlay mode. |
| 132 | + overlay = cv2.addWeighted(input_image, _OVERLAY_ALPHA, |
| 133 | + segmentation_map_image, _OVERLAY_ALPHA, 0) |
| 134 | + elif display_mode == 'side-by-side': |
| 135 | + # Side by side mode. |
| 136 | + overlay = cv2.hconcat([input_image, segmentation_map_image]) |
| 137 | + else: |
| 138 | + sys.exit(f'ERROR: Unsupported display mode: {display_mode}.') |
| 139 | + |
| 140 | + # Show the FPS |
| 141 | + fps_text = 'FPS = ' + str(int(fps)) |
| 142 | + text_location = (_FPS_LEFT_MARGIN, _LEGEND_ROW_SIZE) |
| 143 | + cv2.putText(overlay, fps_text, text_location, cv2.FONT_HERSHEY_PLAIN, |
| 144 | + _LEGEND_FONT_SIZE, _LEGEND_TEXT_COLOR, _LEGEND_FONT_THICKNESS) |
| 145 | + |
| 146 | + # Initialize the origin coordinates of the label. |
| 147 | + legend_x = overlay.shape[1] + _LABEL_MARGIN |
| 148 | + legend_y = overlay.shape[0] // _LEGEND_ROW_SIZE + _LABEL_MARGIN |
| 149 | + |
| 150 | + # Expand the frame to show the label. |
| 151 | + overlay = cv2.copyMakeBorder(overlay, 0, 0, 0, _PADDING_WIDTH_FOR_LEGEND, |
| 152 | + cv2.BORDER_CONSTANT, None, |
| 153 | + _LEGEND_BACKGROUND_COLOR) |
| 154 | + |
| 155 | + # Show the label on right-side frame. |
| 156 | + for colored_label in colored_labels: |
| 157 | + rect_color = colored_label.color |
| 158 | + start_point = (legend_x, legend_y) |
| 159 | + end_point = (legend_x + _LEGEND_RECT_SIZE, legend_y + _LEGEND_RECT_SIZE) |
| 160 | + cv2.rectangle(overlay, start_point, end_point, rect_color, |
| 161 | + -_LEGEND_FONT_THICKNESS) |
| 162 | + |
| 163 | + label_location = legend_x + _LEGEND_RECT_SIZE + _LABEL_MARGIN, legend_y + _LABEL_MARGIN |
| 164 | + cv2.putText(overlay, colored_label.label, label_location, |
| 165 | + cv2.FONT_HERSHEY_PLAIN, _LEGEND_FONT_SIZE, _LEGEND_TEXT_COLOR, |
| 166 | + _LEGEND_FONT_THICKNESS) |
| 167 | + legend_y += (_LEGEND_RECT_SIZE + _LABEL_MARGIN) |
| 168 | + |
| 169 | + return overlay |
| 170 | + |
| 171 | + |
| 172 | +def main(): |
| 173 | + parser = argparse.ArgumentParser( |
| 174 | + formatter_class=argparse.ArgumentDefaultsHelpFormatter) |
| 175 | + parser.add_argument( |
| 176 | + '--model', |
| 177 | + help='Name of image segmentation model.', |
| 178 | + required=False, |
| 179 | + default='deeplabv3.tflite') |
| 180 | + parser.add_argument( |
| 181 | + '--displayMode', |
| 182 | + help='Mode to display image segmentation.', |
| 183 | + required=False, |
| 184 | + default='overlay') |
| 185 | + parser.add_argument( |
| 186 | + '--numThreads', |
| 187 | + help='Number of CPU threads to run the model.', |
| 188 | + required=False, |
| 189 | + default=4) |
| 190 | + parser.add_argument( |
| 191 | + '--enableEdgeTPU', |
| 192 | + help='Whether to run the model on EdgeTPU.', |
| 193 | + action='store_true', |
| 194 | + required=False, |
| 195 | + default=False) |
| 196 | + parser.add_argument( |
| 197 | + '--cameraId', help='Id of camera.', required=False, default=0) |
| 198 | + parser.add_argument( |
| 199 | + '--frameWidth', |
| 200 | + help='Width of frame to capture from camera.', |
| 201 | + required=False, |
| 202 | + default=640) |
| 203 | + parser.add_argument( |
| 204 | + '--frameHeight', |
| 205 | + help='Height of frame to capture from camera.', |
| 206 | + required=False, |
| 207 | + default=480) |
| 208 | + args = parser.parse_args() |
| 209 | + |
| 210 | + run(args.model, args.displayMode, int(args.numThreads), |
| 211 | + bool(args.enableEdgeTPU), int(args.cameraId), args.frameWidth, |
| 212 | + args.frameHeight) |
| 213 | + |
| 214 | + |
| 215 | +if __name__ == '__main__': |
| 216 | + main() |
0 commit comments