/
cat_detection_image.py
64 lines (55 loc) · 2.24 KB
/
cat_detection_image.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#!/usr/bin/env python3
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Modified Object detection library demo from chadwallacehart.
Original file:
https://github.com/google/aiyprojects-raspbian/blob/aiyprojects/src/examples/vision/object_detection.py
- Takes an input image and tries to detect person or cat.
- Draws bounding boxes around detected objects.
- Saves an image with bounding boxes around detected objects.
"""
import argparse
import io
import sys
from PIL import Image
from PIL import ImageDraw
from aiy.vision.inference import ImageInference
# from aiy.vision.models import object_detection
# Use my modified file instead
import aiy_cat_detection
def _crop_center(image):
width, height = image.size
size = min(width, height)
x, y = (width - size) / 2, (height - size) / 2
return image.crop((x, y, x + size, y + size)), (x, y)
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', '-i', dest='input', required=True)
parser.add_argument('--output', '-o', dest='output')
args = parser.parse_args()
with ImageInference(aiy_cat_detection.model()) as inference:
image = Image.open(
io.BytesIO(sys.stdin.buffer.read())
if args.input == '-' else args.input)
image_center, offset = _crop_center(image)
draw = ImageDraw.Draw(image)
result = inference.run(image_center)
for i, obj in enumerate(aiy_cat_detection.get_objects(result, 0.3, offset)):
print('Object #%d: %s' % (i, str(obj)))
x, y, width, height = obj.bounding_box
draw.rectangle((x, y, x + width, y + height), outline='red')
if args.output:
image.save(args.output)
if __name__ == '__main__':
main()