Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
2
2021_214
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Analytics
Analytics
CI / CD
Repository
Value Stream
Wiki
Wiki
Snippets
Snippets
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
Chellapillai C.V.S
2021_214
Commits
18ae2d6f
Commit
18ae2d6f
authored
Nov 26, 2021
by
Chellapillai C.V.S
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Added
parent
19b0b8be
Changes
3
Expand all
Hide whitespace changes
Inline
Side-by-side
Showing
3 changed files
with
1844 additions
and
0 deletions
+1844
-0
.ipynb_checkpoints/image_based_food_calorie_estimation -checkpoint.ipynb
...nts/image_based_food_calorie_estimation -checkpoint.ipynb
+810
-0
food.py
food.py
+224
-0
image_based_food_calorie_estimation .ipynb
image_based_food_calorie_estimation .ipynb
+810
-0
No files found.
.ipynb_checkpoints/image_based_food_calorie_estimation -checkpoint.ipynb
0 → 100644
View file @
18ae2d6f
This diff is collapsed.
Click to expand it.
food.py
0 → 100644
View file @
18ae2d6f
import
os
import
sys
import
json
import
datetime
import
numpy
as
np
import
skimage.draw
import
cv2
from
mrcnn.visualize
import
display_instances
import
matplotlib.pyplot
as
plt
# Root directory of the project
ROOT_DIR
=
"E:
\
Calories"
# Import Mask RCNN
sys
.
path
.
append
(
ROOT_DIR
)
# To find local version of the library
from
mrcnn.config
import
Config
from
mrcnn
import
model
as
modellib
,
utils
calorie_per_sq_inch
=
{
'smashed potatoes'
:
1.4778
,
'carrots'
:
0.7256
,
'spanich'
:
0.4102
,
'veal breaded cutlet'
:
4.4247
,
'scallops'
:
0.9823
,
'beans'
:
0.5486
,
'pizza'
:
6.2477
,
'pasta'
:
3.5398
}
# Path to trained weights file
COCO_WEIGHTS_PATH
=
os
.
path
.
join
(
ROOT_DIR
,
"mask_rcnn_coco.h5"
)
# Directory to save logs and model checkpoints, if not provided
# through the command line argument --logs
DEFAULT_LOGS_DIR
=
os
.
path
.
join
(
ROOT_DIR
,
"logs"
)
def
get_calorie
(
class_name
,
real_food_area
):
if
class_name
in
calorie_per_unit
:
return
calorie_per_unit
[
class_name
]
else
:
return
calorie_per_sq_inch
[
class_name
]
*
real_food_area
class
CustomConfig
(
Config
):
"""Configuration for training on the custom dataset.
Derives from the base Config class and overrides some values.
"""
# Give the configuration a recognizable name
NAME
=
"food"
# We use a GPU with 12GB memory, which can fit two images.
# Adjust down if you use a smaller GPU.
IMAGES_PER_GPU
=
2
# Number of classes (including background)
NUM_CLASSES
=
1
+
10
# Number of training steps per epoch
STEPS_PER_EPOCH
=
250
# Skip detections with < 90% confidence
DETECTION_MIN_CONFIDENCE
=
0.9
############################################################
# Dataset
############################################################
class
CustomDataset
(
utils
.
Dataset
):
def
load_custom
(
self
,
dataset_dir
,
subset
):
"""Load a subset of the Dog-Cat dataset.
dataset_dir: Root directory of the dataset.
subset: Subset to load: train or val
"""
# Add classes. We have only one class to add.
self
.
add_class
(
"food"
,
1
,
"mashed potatoes"
)
self
.
add_class
(
"food"
,
2
,
"pasta"
)
self
.
add_class
(
"food"
,
3
,
"pizza"
)
self
.
add_class
(
"food"
,
4
,
"beans"
)
self
.
add_class
(
"food"
,
5
,
"chicken"
)
self
.
add_class
(
"food"
,
6
,
"orange"
)
self
.
add_class
(
"food"
,
7
,
"yogurt"
)
self
.
add_class
(
"food"
,
8
,
"spinach"
)
self
.
add_class
(
"food"
,
9
,
"bread"
)
self
.
add_class
(
"food"
,
10
,
"veal breaded cutlet"
)
# Train or validation dataset?
assert
subset
in
[
"train"
,
"val"
]
dataset_dir
=
os
.
path
.
join
(
dataset_dir
,
subset
)
# Load annotations
# VGG Image Annotator saves each image in the form:
# { 'filename': '28503151_5b5b7ec140_b.jpg',
# 'regions': {
# '0': {
# 'region_attributes': {},
# 'shape_attributes': {
# 'all_points_x': [...],
# 'all_points_y': [...],
# 'name': 'polygon'}},
# ... more regions ...
# },
# 'size': 100202
# }
# We mostly care about the x and y coordinates of each region
annotations1
=
json
.
load
(
open
(
r'E:\Calories\dataset\train\annotation.json'
))
#annotations2 = json.load(open(r'E:\Calories\dataset\val\demo_json.json'))
# print(annotations1)
annotations
=
list
(
annotations1
.
values
())
# don't need the dict keys
# The VIA tool saves images in the JSON even if they don't have any
# annotations. Skip unannotated images.
annotations
=
[
a
for
a
in
annotations
if
a
[
'regions'
]]
# Add images
for
a
in
annotations
:
# print(a)
# Get the x, y coordinaets of points of the polygons that make up
# the outline of each object instance. There are stores in the
# shape_attributes (see json format above)
polygons
=
[
r
[
'shape_attributes'
]
for
r
in
a
[
'regions'
]]
objects
=
[
s
[
'region_attributes'
][
'food'
]
for
s
in
a
[
'regions'
]]
print
(
"objects:"
,
objects
)
#name_dict = {"laptop": 1,"tab": 2,"phone": 3}
name_dict
=
{
"mashed potatoes"
:
1
,
"pasta"
:
2
,
"pizza"
:
3
,
"beans"
:
4
,
"chicken"
:
5
,
"orange"
:
6
,
"yogurt"
:
7
,
"spinach"
:
8
,
"bread"
:
9
,
"veal breaded cutlet"
:
10
}
# key = tuple(name_dict)
num_ids
=
[
name_dict
[
a
]
for
a
in
objects
]
# num_ids = [int(n['Event']) for n in objects]
# load_mask() needs the image size to convert polygons to masks.
# Unfortunately, VIA doesn't include it in JSON, so we must read
# the image. This is only managable since the dataset is tiny.
print
(
"numids"
,
num_ids
)
image_path
=
os
.
path
.
join
(
dataset_dir
,
a
[
'filename'
])
image
=
skimage
.
io
.
imread
(
image_path
)
height
,
width
=
image
.
shape
[:
2
]
self
.
add_image
(
"food"
,
## for a single class just add the name here
image_id
=
a
[
'filename'
],
# use file name as a unique image id
path
=
image_path
,
width
=
width
,
height
=
height
,
polygons
=
polygons
,
num_ids
=
num_ids
)
def
load_mask
(
self
,
image_id
):
"""Generate instance masks for an image.
Returns:
masks: A bool array of shape [height, width, instance count] with
one mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# If not a Dog-Cat dataset image, delegate to parent class.
image_info
=
self
.
image_info
[
image_id
]
if
image_info
[
"source"
]
!=
"food"
:
return
super
(
self
.
__class__
,
self
)
.
load_mask
(
image_id
)
# Convert polygons to a bitmap mask of shape
# [height, width, instance_count]
info
=
self
.
image_info
[
image_id
]
if
info
[
"source"
]
!=
"food"
:
return
super
(
self
.
__class__
,
self
)
.
load_mask
(
image_id
)
num_ids
=
info
[
'num_ids'
]
mask
=
np
.
zeros
([
info
[
"height"
],
info
[
"width"
],
len
(
info
[
"polygons"
])],
dtype
=
np
.
uint8
)
for
i
,
p
in
enumerate
(
info
[
"polygons"
]):
# Get indexes of pixels inside the polygon and set them to 1
rr
,
cc
=
skimage
.
draw
.
polygon
(
p
[
'all_points_y'
],
p
[
'all_points_x'
])
mask
[
rr
,
cc
,
i
]
=
1
# Return mask, and array of class IDs of each instance. Since we have
# one class ID only, we return an array of 1s
# Map class names to class IDs.
num_ids
=
np
.
array
(
num_ids
,
dtype
=
np
.
int32
)
return
mask
,
num_ids
#np.ones([mask.shape[-1]], dtype=np.int32)
def
image_reference
(
self
,
image_id
):
"""Return the path of the image."""
info
=
self
.
image_info
[
image_id
]
if
info
[
"source"
]
==
"food"
:
return
info
[
"path"
]
else
:
super
(
self
.
__class__
,
self
)
.
image_reference
(
image_id
)
def
train
(
model
):
"""Train the model."""
# Training dataset.
dataset_train
=
CustomDataset
()
dataset_train
.
load_custom
(
r"E:\Calories\dataset"
,
"train"
)
dataset_train
.
prepare
()
# Validation dataset
dataset_val
=
CustomDataset
()
dataset_val
.
load_custom
(
r"E:\Calories\dataset"
,
"val"
)
dataset_val
.
prepare
()
# *** This training schedule is an example. Update to your needs ***
# Since we're using a very small dataset, and starting from
# COCO trained weights, we don't need to train too long. Also,
# no need to train all layers, just the heads should do it.
print
(
"Training network heads"
)
model
.
train
(
dataset_train
,
dataset_val
,
learning_rate
=
config
.
LEARNING_RATE
,
epochs
=
250
,
layers
=
'heads'
)
config
=
CustomConfig
()
model
=
modellib
.
MaskRCNN
(
mode
=
"training"
,
config
=
config
,
model_dir
=
DEFAULT_LOGS_DIR
)
weights_path
=
COCO_WEIGHTS_PATH
# Download weights file
if
not
os
.
path
.
exists
(
weights_path
):
utils
.
download_trained_weights
(
weights_path
)
model
.
load_weights
(
weights_path
,
by_name
=
True
,
exclude
=
[
"mrcnn_class_logits"
,
"mrcnn_bbox_fc"
,
"mrcnn_bbox"
,
"mrcnn_mask"
])
train
(
model
)
\ No newline at end of file
image_based_food_calorie_estimation .ipynb
0 → 100644
View file @
18ae2d6f
This diff is collapsed.
Click to expand it.
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment