Skip to content

Commit c36f932

Browse files
authored
Add files via upload
1 parent 22d1439 commit c36f932

File tree

4 files changed

+1340
-13
lines changed

4 files changed

+1340
-13
lines changed

detection_images.py

+162
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
from object_detection.utils import visualization_utils as vis_util
2+
from object_detection.utils import label_map_util
3+
from object_detection.utils import ops as utils_ops
4+
import numpy as np
5+
import os
6+
import six.moves.urllib as urllib
7+
import sys
8+
import tarfile
9+
import tensorflow as tf
10+
import zipfile
11+
12+
from collections import defaultdict
13+
from io import StringIO
14+
from matplotlib import pyplot as plt
15+
from PIL import Image
16+
import os
17+
import glob
18+
19+
# Path to frozen detection graph. This is the actual model that is used for the object detection.
20+
PATH_TO_CKPT = './graphs/frozen_inference_graph.pb'
21+
22+
# List of the strings that is used to add correct label for each box.
23+
PATH_TO_LABELS = './graphs/label_map.pbtxt'
24+
25+
# Path to the images you want to infer
26+
PATH_TO_TEST_IMAGES_DIR = './images'
27+
28+
assert os.path.isfile('./graphs/frozen_inference_graph.pb')
29+
assert os.path.isfile(PATH_TO_LABELS)
30+
31+
TEST_IMAGE_PATHS = glob.glob(os.path.join(PATH_TO_TEST_IMAGES_DIR, "*.*"))
32+
assert len(TEST_IMAGE_PATHS) > 0, 'No image found in `{}`.'.format(
33+
PATH_TO_TEST_IMAGES_DIR)
34+
35+
try:
36+
37+
detection_graph = tf.Graph()
38+
with detection_graph.as_default():
39+
od_graph_def = tf.GraphDef()
40+
with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid:
41+
serialized_graph = fid.read()
42+
od_graph_def.ParseFromString(serialized_graph)
43+
tf.import_graph_def(od_graph_def, name='')
44+
45+
label_map = label_map_util.load_labelmap(PATH_TO_LABELS)
46+
categories = label_map_util.convert_label_map_to_categories(
47+
label_map, max_num_classes=36, use_display_name=True)
48+
category_index = label_map_util.create_category_index(categories)
49+
50+
def load_image_into_numpy_array(image):
51+
(im_width, im_height) = image.size
52+
return np.array(image.getdata()).reshape(
53+
(im_height, im_width, 3)).astype(np.uint8)
54+
55+
def get_files_on_directory(path):
56+
directory = os.path.basename(path)
57+
file_list = os.listdir(directory)
58+
return file_list
59+
60+
def run_inference_for_single_image(image, graph):
61+
with graph.as_default():
62+
with tf.Session() as sess:
63+
# Get handles to input and output tensors
64+
ops = tf.get_default_graph().get_operations()
65+
all_tensor_names = {
66+
output.name for op in ops for output in op.outputs}
67+
tensor_dict = {}
68+
for key in [
69+
'num_detections', 'detection_boxes', 'detection_scores',
70+
'detection_classes', 'detection_masks'
71+
]:
72+
tensor_name = key + ':0'
73+
if tensor_name in all_tensor_names:
74+
tensor_dict[key] = tf.get_default_graph().get_tensor_by_name(
75+
tensor_name)
76+
if 'detection_masks' in tensor_dict:
77+
# The following processing is only for single image
78+
detection_boxes = tf.squeeze(
79+
tensor_dict['detection_boxes'], [0])
80+
detection_masks = tf.squeeze(
81+
tensor_dict['detection_masks'], [0])
82+
# Reframe is required to translate mask from box coordinates to image coordinates and fit the image size.
83+
real_num_detection = tf.cast(
84+
tensor_dict['num_detections'][0], tf.int32)
85+
detection_boxes = tf.slice(detection_boxes, [0, 0], [
86+
real_num_detection, -1])
87+
detection_masks = tf.slice(detection_masks, [0, 0, 0], [
88+
real_num_detection, -1, -1])
89+
detection_masks_reframed = utils_ops.reframe_box_masks_to_image_masks(
90+
detection_masks, detection_boxes, image.shape[0], image.shape[1])
91+
detection_masks_reframed = tf.cast(
92+
tf.greater(detection_masks_reframed, 0.5), tf.uint8)
93+
# Follow the convention by adding back the batch dimension
94+
tensor_dict['detection_masks'] = tf.expand_dims(
95+
detection_masks_reframed, 0)
96+
image_tensor = tf.get_default_graph().get_tensor_by_name('image_tensor:0')
97+
98+
# Run inference
99+
output_dict = sess.run(tensor_dict,
100+
feed_dict={image_tensor: np.expand_dims(image, 0)})
101+
102+
# all outputs are float32 numpy arrays, so convert types as appropriate
103+
output_dict['num_detections'] = int(
104+
output_dict['num_detections'][0])
105+
output_dict['detection_classes'] = output_dict[
106+
'detection_classes'][0].astype(np.uint8)
107+
output_dict['detection_boxes'] = output_dict['detection_boxes'][0]
108+
output_dict['detection_scores'] = output_dict['detection_scores'][0]
109+
if 'detection_masks' in output_dict:
110+
output_dict['detection_masks'] = output_dict['detection_masks'][0]
111+
return output_dict
112+
113+
count = 1
114+
for image_path in TEST_IMAGE_PATHS:
115+
image = Image.open(image_path)
116+
print(image_path)
117+
118+
119+
if '.jpg' not in image_path:
120+
continue
121+
if sys.platform == 'win32':
122+
image_name = image_path.split('\\')[1].split('.')[0]
123+
else:
124+
image_name = image_path.split('/')[2].split('.')[0]
125+
126+
im_width, im_height = image.size
127+
128+
im_width_inche = im_width // 77
129+
im_height_inche = im_height // 77 #redimensioning the image resolution
130+
131+
IMAGE_SIZE = (im_width_inche, im_height_inche)
132+
133+
# the array based representation of the image will be used later in order to prepare the
134+
# result image with boxes and labels on it.
135+
image_np = load_image_into_numpy_array(image)
136+
# Expand dimensions since the model expects images to have e:[1 shap, None, None, 3]
137+
image_np_expanded = np.expand_dims(image_np, axis=0)
138+
# Actual detection.
139+
output_dict = run_inference_for_single_image(image_np, detection_graph)
140+
141+
# Visualization of the results of a detection.
142+
vis_util.visualize_boxes_and_labels_on_image_array(
143+
image_np,
144+
output_dict['detection_boxes'],
145+
output_dict['detection_classes'],
146+
output_dict['detection_scores'],
147+
category_index,
148+
instance_masks=output_dict.get('detection_masks'),
149+
use_normalized_coordinates=True,
150+
line_thickness=10,
151+
file_name=image_name
152+
)
153+
154+
plt.figure(figsize=IMAGE_SIZE)
155+
plt.axis('off')
156+
plt.imshow(image_np)
157+
158+
plt.savefig('./results/image_' + image_name + '.jpg', bbox_inches='tight')
159+
count += 1
160+
161+
except Exception as error:
162+
print(error)

generate_xml.py

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
import xml.etree.cElementTree as ET
2+
from random import randrange
3+
import os
4+
5+
class GenerateXml(object):
6+
def __init__(self, box_array, im_width, im_height, inferred_class, filename):
7+
self.inferred_class = inferred_class
8+
self.box_array = box_array
9+
self.im_width = im_width
10+
self.im_height = im_height
11+
self.file_name = filename
12+
13+
def get_file_name(self):
14+
xml_path = './xml'
15+
directory = os.path.basename(xml_path)
16+
file_list = os.listdir(directory)
17+
18+
if len(file_list) == 0:
19+
return 1
20+
else:
21+
return len(file_list) + 1
22+
23+
def gerenate_basic_structure(self):
24+
file_name = "image" + "_" + str(self.file_name)
25+
annotation = ET.Element("annotation")
26+
ET.SubElement(annotation, "filename").text = file_name + ".jpg"
27+
size = ET.SubElement(annotation, "size")
28+
ET.SubElement(size, "width").text = str(self.im_width)
29+
ET.SubElement(size, "height").text = str(self.im_height)
30+
ET.SubElement(size, "depth").text = "3"
31+
32+
for i in self.box_array:
33+
objectBox = ET.SubElement(annotation, "object")
34+
ET.SubElement(objectBox, "name").text = self.inferred_class
35+
ET.SubElement(objectBox, "pose").text = "Unspecified"
36+
ET.SubElement(objectBox, "truncated").text = "0"
37+
ET.SubElement(objectBox, "difficult").text = "0"
38+
bndBox = ET.SubElement(objectBox, "bndbox")
39+
ET.SubElement(bndBox, "xmin").text = str(i['xmin'])
40+
ET.SubElement(bndBox, "ymin").text = str(i['ymin'])
41+
ET.SubElement(bndBox, "xmax").text = str(i['xmax'])
42+
ET.SubElement(bndBox, "ymax").text = str(i['ymax'])
43+
44+
arquivo = ET.ElementTree(annotation)
45+
arquivo.write("./xml/" + file_name + ".xml")
46+
47+
def main():
48+
xml = GenerateXml([{'xmin': 0.5406094193458557, 'xmax': 0.6001364588737488, 'ymin': 0.6876631379127502, 'ymax': 0.7547240853309631}, {'xmin': 0.5406094193458557, 'xmax': 0.6001364588737488, 'ymin': 0.6876631379127502, 'ymax': 0.7547240853309631}, {'xmin': 0.5406094193458557, 'xmax': 0.6001364588737488, 'ymin': 0.6876631379127502, 'ymax': 0.7547240853309631}, {'xmin': 0.5406094193458557, 'xmax': 0.6001364588737488, 'ymin': 0.6876631379127502, 'ymax': 0.7547240853309631}], '4000', '2000', 'miner', 'fewhakko') # just for debuggind
49+
xml.gerenate_basic_structure()

readme.md

+5-13
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,14 @@
1-
![auto-annotate-logo](https://raw.githubusercontent.com/Lucs1590/auto_annotate/master/images/logo.png)
2-
# Auto-annotate
3-
### Welcome to the auto-annotate images for TensorFlow object detection!
4-
5-
You are tired to label your images by hand to work with object detection? So, this project will make your life easier, just annotate some images and let the machine do the rest for you!
1+
### Welcome to the auto-annotate images for object detection!
62

73
## Requirements
8-
- You will need to [clone the TensorFlow repository](https://github.com/tensorflow/models)
9-
- Install the [dependencies](https://tensorflow-object-detection-api-tutorial.readthedocs.io/en/tensorflow-1.14/install.html) for object detection
10-
11-
**note:** This project is compatible with TF>=1.4
4+
- You will need to clone the tensorflow repository: https://github.com/tensorflow/models
5+
- Install the dependencies: https://github.com/tensorflow/models/blob/master/research/object_detection/g3doc/installation.md
6+
- Install the xElementTree dependency via pip
127
## How to run
138
- Copy and paste the file generate_xml.py and visualization_utils.py into the **research/object_detection/utils** in the tensorflow repo.
149
- Add your pre-treined model and label map into the 'graphs' folder.
1510
- Add the images you want to label into the images folder
1611
- Change the xml path in generate_xml.py to put your own local path.
1712
- Inside the auto_annotate folder run: **python3 scripts/detection_images.py**
1813
- If everything is ok you will see the inference results and the xml in your respective folders!
19-
- If you have trouble or doubt check my [tutorial on medium](https://medium.com/@alvaroleandrocavalcante/auto-annotate-images-for-tensorflow-object-detection-19b59f31c4d9?sk=0a189a8af4874462c1977c6f6738d759)
20-
21-
## Any trouble?
22-
Don't worry, open a issue and I'll hep you!
14+
- If you have trouble or doubt see my tutorial on medium: https://medium.com/@alvaroleandrocavalcante/auto-annotate-images-for-tensorflow-object-detection-19b59f31c4d9?sk=0a189a8af4874462c1977c6f6738d759

0 commit comments

Comments
 (0)