-
Notifications
You must be signed in to change notification settings - Fork 905
added darknet reference and darknet tiny classifiers #201
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 2 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
193f9a5
added darknet reference and darknet tiny classifiers
hiddentn 26769e9
fixed linting stuff
hiddentn 46527fa
edits..
hiddentn 978ff99
edits2.0
hiddentn 009623f
Merge branch 'master' into darknetclassifier
cvalenzuela 456a212
Merge branch 'master' into darknetclassifier
cvalenzuela 3118bcd
Merge branch 'master' into darknetclassifier
cvalenzuela 4cf7f6a
clean comments
cvalenzuela File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,140 @@ | ||
// Copyright (c) 2018 ml5 | ||
// | ||
// This software is released under the MIT License. | ||
// https://opensource.org/licenses/MIT | ||
|
||
import * as tf from '@tensorflow/tfjs'; | ||
import IMAGENET_CLASSES_DARKNET from '../utils/IMAGENET_CLASSES_DARKNET'; | ||
|
||
const DEFAULTS = { | ||
DARKNET_URL: 'https://rawgit.com/TheHidden1/ml5-data-and-models/darknetclassifier/models/darknetclassifier/darknetreference/model.json', | ||
DARKNET_TINY_URL: 'https://rawgit.com/TheHidden1/ml5-data-and-models/darknetclassifier/models/darknetclassifier/darknettiny/model.json', | ||
IMAGE_SIZE_DARKNET: 256, | ||
IMAGE_SIZE_DARKNET_TINY: 224, | ||
}; | ||
|
||
|
||
async function getTopKClasses(logits, topK) { | ||
const values = await logits.data(); | ||
const valuesAndIndices = []; | ||
for (let i = 0; i < values.length; i += 1) { | ||
valuesAndIndices.push({ | ||
value: values[i], | ||
index: i, | ||
}); | ||
} | ||
valuesAndIndices.sort((a, b) => b.value - a.value); | ||
|
||
const topkValues = new Float32Array(topK); | ||
const topkIndices = new Int32Array(topK); | ||
for (let i = 0; i < topK; i += 1) { | ||
topkValues[i] = valuesAndIndices[i].value; | ||
topkIndices[i] = valuesAndIndices[i].index; | ||
} | ||
|
||
const topClassesAndProbs = []; | ||
for (let i = 0; i < topkIndices.length; i += 1) { | ||
topClassesAndProbs.push({ | ||
className: IMAGENET_CLASSES_DARKNET[topkIndices[i]], | ||
probability: topkValues[i], | ||
}); | ||
} | ||
return topClassesAndProbs; | ||
} | ||
|
||
function preProcess(img, size) { | ||
let image; | ||
if (!(img instanceof tf.Tensor)) { | ||
if (img instanceof HTMLImageElement || img instanceof HTMLVideoElement) { | ||
image = tf.fromPixels(img); | ||
} else if (typeof img === 'object' && (img.elt instanceof HTMLImageElement || img.elt instanceof HTMLVideoElement)) { | ||
image = tf.fromPixels(img.elt); // Handle p5.js image and video. | ||
} | ||
} else { | ||
image = img; | ||
} | ||
// Normalize the image from [0, 255] to [0, 1]. | ||
const normalized = image.toFloat().div(tf.scalar(255)); | ||
let resized = normalized; | ||
if (normalized.shape[0] !== size || normalized.shape[1] !== size) { | ||
const alignCorners = true; | ||
resized = tf.image.resizeBilinear(normalized, [size, size], alignCorners); | ||
} | ||
// Reshape to a single-element batch so we can pass it to predict. | ||
const batched = resized.reshape([1, size, size, 3]); | ||
// Scale Stuff | ||
// this.scaleX = this.imgHeight / this.inputHeight; | ||
// this.scaleY = this.imgWidth / this.inputWidth; | ||
return batched; | ||
} | ||
export class Darknet { | ||
constructor(version) { | ||
this.version = version; | ||
switch (this.version) { | ||
case 'reference': | ||
this.imgSize = DEFAULTS.IMAGE_SIZE_DARKNET; | ||
break; | ||
case 'tiny': | ||
this.imgSize = DEFAULTS.IMAGE_SIZE_DARKNET_TINY; | ||
break; | ||
|
||
default: | ||
break; | ||
} | ||
} | ||
|
||
async load() { | ||
switch (this.version) { | ||
// might add darknet_448 | ||
case 'reference': | ||
this.model = await tf.loadModel(DEFAULTS.DARKNET_URL); | ||
break; | ||
|
||
case 'tiny': | ||
this.model = await tf.loadModel(DEFAULTS.DARKNET_TINY_URL); | ||
break; | ||
|
||
default: | ||
break; | ||
} | ||
|
||
// Warmup the model. | ||
const result = tf.tidy(() => this.model.predict(tf.zeros([1, this.imgSize, this.imgSize, 3]))); | ||
await result.data(); | ||
result.dispose(); | ||
} | ||
|
||
/** | ||
* Classifies an image from the 1000 ImageNet classes returning a map of | ||
* the most likely class names to their probability. | ||
* | ||
* @param img The image to classify. Can be a tensor or a DOM element image, | ||
* video, or canvas. | ||
* @param topk How many top values to use. Defaults to 3. | ||
*/ | ||
async classify(img, topk = 3) { | ||
const logits = tf.tidy(() => { | ||
const imgData = preProcess(img, this.imgSize); | ||
const predictions = this.model.predict(imgData); | ||
return tf.softmax(predictions); | ||
}); | ||
const classes = await getTopKClasses(logits, topk); | ||
logits.dispose(); | ||
return classes; | ||
} | ||
} | ||
|
||
|
||
export async function load(version) { | ||
if (tf == null) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Not sure we need this validation here. TF.js comes with ml5.js |
||
throw new Error('Cannot find TensorFlow.js. If you are using a <script> tag, please ' + | ||
'also include @tensorflow/tfjs on the page before using this model.'); | ||
} | ||
if (version !== 'reference' && version !== 'tiny') { | ||
throw new Error('Please select a version : darknet-reference or darknet-tiny'); | ||
} | ||
|
||
const darknet = new Darknet(version); | ||
await darknet.load(); | ||
return darknet; | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Just a reminder that we need to change this to the ones hosted in the ml5.js models
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
i made a pull request on ml5js/ml5-data-and-models#32
can you merge it ?