EdjeElectronics / TensorFlow-Object-Detection-API-Tutorial-Train-Multiple-Objects-Windows-10

How to train a TensorFlow Object Detection Classifier for multiple object detection on Windows
Apache License 2.0
2.91k stars 1.3k forks source link

How to export the images in the bounding boxes as .jpg #220

Open danielfbg opened 5 years ago

danielfbg commented 5 years ago

Hi,

for my project I want to save the parts of an image enclosed by the Bounding Boxes as .jpg for feeding in another CNN for further classification.

How can I adjust the code so i get the sub-images out of my input- image ?

import os
import cv2
import numpy as np
import tensorflow as tf
import sys

# This is needed since the notebook is stored in the object_detection folder.
sys.path.append("..")

# Import utilites
from utils import label_map_util
from utils import visualization_utils as vis_util

# Name of the directory containing the object detection module we're using
MODEL_NAME = 'inference_graph'
IMAGE_NAME = 'test1.jpg'

# Grab path to current working directory
CWD_PATH = os.getcwd()

# Path to frozen detection graph .pb file, which contains the model that is used
# for object detection.
PATH_TO_CKPT = os.path.join(CWD_PATH,MODEL_NAME,'frozen_inference_graph.pb')

# Path to label map file
PATH_TO_LABELS = os.path.join(CWD_PATH,'training','labelmap.pbtxt')

# Path to image
PATH_TO_IMAGE = os.path.join(CWD_PATH,IMAGE_NAME)

# Number of classes the object detector can identify
NUM_CLASSES = 6

# Load the label map.
# Label maps map indices to category names, so that when our convolution
# network predicts `5`, we know that this corresponds to `king`.
# Here we use internal utility functions, but anything that returns a
# dictionary mapping integers to appropriate string labels would be fine
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
categories = label_map_util.convert_label_map_to_categories(label_map, max_num_classes=NUM_CLASSES, use_display_name=True)
category_index = label_map_util.create_category_index(categories)

# Load the Tensorflow model into memory.
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='')

    sess = tf.Session(graph=detection_graph)

# Define input and output tensors (i.e. data) for the object detection classifier

# Input tensor is the image
image_tensor = detection_graph.get_tensor_by_name('image_tensor:0')

# Output tensors are the detection boxes, scores, and classes
# 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 represents level of confidence for each of the objects.
# The 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')

# Number of objects detected
num_detections = detection_graph.get_tensor_by_name('num_detections:0')

# Load image using OpenCV and
# expand image dimensions to have shape: [1, None, None, 3]
# i.e. a single-column array, where each item in the column has the pixel RGB value
image = cv2.imread(PATH_TO_IMAGE)
image_expanded = np.expand_dims(image, axis=0)

# Perform the actual detection by running the model with the image as input
(boxes, scores, classes, num) = sess.run(
    [detection_boxes, detection_scores, detection_classes, num_detections],
    feed_dict={image_tensor: image_expanded})

# Draw the results of the detection (aka 'visulaize the results')

vis_util.visualize_boxes_and_labels_on_image_array(
    image,
    np.squeeze(boxes),
    np.squeeze(classes).astype(np.int32),
    np.squeeze(scores),
    category_index,
    use_normalized_coordinates=True,
    line_thickness=8,
    min_score_thresh=0.80)

# All the results have been drawn on image. Now display the image.
cv2.imshow('Object detector', image)

# Press any key to close the image
cv2.waitKey(0)

# Clean up
cv2.destroyAllWindows()
Lhogeshwaran commented 4 years ago

Found the below solution in one of the issues while looking for the same thing. In /utils/visualization_utils.py update the following piece of code

def return_coordinates( image, boxes, classes, scores, category_index, instance_masks=None, instance_boundaries=None, keypoints=None, use_normalized_coordinates=False, max_boxes_to_draw=20, min_score_thresh=.5, agnostic_mode=False, line_thickness=4, groundtruth_box_visualization_color='black', skip_scores=False, skip_labels=False):

Create a display string (and color) for every box location, group any boxes

that correspond to the same location.

    box_to_display_str_map = collections.defaultdict(list)
    box_to_color_map = collections.defaultdict(str)
    box_to_instance_masks_map = {}
    box_to_instance_boundaries_map = {}
    box_to_score_map = {}
    box_to_keypoints_map = collections.defaultdict(list)
    if not max_boxes_to_draw:
      max_boxes_to_draw = boxes.shape[0]
    for i in range(min(max_boxes_to_draw, boxes.shape[0])):
      if scores is None or scores[i] > min_score_thresh:
        box = tuple(boxes[i].tolist())
        if instance_masks is not None:
          box_to_instance_masks_map[box] = instance_masks[i]
        if instance_boundaries is not None:
          box_to_instance_boundaries_map[box] = instance_boundaries[i]
        if keypoints is not None:
          box_to_keypoints_map[box].extend(keypoints[i])
        if scores is None:
          box_to_color_map[box] = groundtruth_box_visualization_color
        else:
          display_str = ''
          if not skip_labels:
            if not agnostic_mode:
              if classes[i] in category_index.keys():
                class_name = category_index[classes[i]]['name']
              else:
                class_name = 'N/A'
              display_str = str(class_name)
          if not skip_scores:
            if not display_str:
              display_str = '{}%'.format(int(100*scores[i]))
            else:
              display_str = '{}: {}%'.format(display_str, int(100*scores[i]))
          box_to_display_str_map[box].append(display_str)
          box_to_score_map[box] = scores[i]
          if agnostic_mode:
            box_to_color_map[box] = 'DarkOrange'
          else:
            box_to_color_map[box] = STANDARD_COLORS[
                classes[i] % len(STANDARD_COLORS)]

    # Draw all boxes onto image.
    coordinates_list = []
    counter_for = 0
    for box, color in box_to_color_map.items():
      ymin, xmin, ymax, xmax = box
      height, width, channels = image.shape
      ymin = int(ymin*height)
      ymax = int(ymax*height)
      xmin = int(xmin*width)
      xmax = int(xmax*width)
      coordinates_list.append([ymin, ymax, xmin, xmax, (box_to_score_map[box]*100), class_name])
      counter_for = counter_for + 1

    return coordinates_list

Update Object_detection_image.py with -

Extract the items as seperate images and store them in /extracted_images

im = 0 for coordinate in coordinates: (y1, y2, x1, x2, acc, classification) = coordinate height = y2-y1 width = x2-x1 crop = image[y1:y1+height, x1:x1+width] EXT_PATH = os.path.join(CWD_PATH, 'extracted_images') name = str(classification)+str(im)+'.png' cv2.imwrite(os.path.join(EXT_PATH, name), crop) im += 1

Extract the text present in images and return them as json

a = extractor.list_files(CWD_PATH) data_dict = {} # Dictionary to collect the data in the image as key:value pairs
for i in a: k = str(i[:4]) c = extractor.tess(os.path.join(CWD_PATH, 'extracted_images', i)) data_dict[k] = c data_json = json.dumps(data_dict) for k,v in data_dict.items(): print(k,v)

suravijayjilla commented 4 years ago

Hi,

extractor is python package? If I run the object_detection_image.py file after update the above codes the visualization_utils return_coordinate function returns only a empty list.

please give any solution for this error...