Skip to content

Instantly share code, notes, and snippets.

@hawkeye64
Created August 27, 2018 19:18
Show Gist options
  • Save hawkeye64/24f56ac2a4b3511a7e3c25ccdc859405 to your computer and use it in GitHub Desktop.
Save hawkeye64/24f56ac2a4b3511a7e3c25ccdc859405 to your computer and use it in GitHub Desktop.
Update Image Example
/**
* Generate a random color
*/
const getRandomColor = () => new cv.Vec(Math.random() * 255, Math.random() * 255, Math.random() * 255);
/**
* Returns a function that, for each prediction, draws a rect area with rndom color
* @param {Arry} predictions Array of predictions
*/
const makeDrawClassDetections = (predictions) => (drawImg, getColor, thickness = 2) => {
predictions
.forEach((p) => {
let color = getColor()
let confidence = p.confidence
let rect = p.rect
let className = classes[p.classIndex]
drawRect(className, confidence, drawImg, rect, color, { thickness })
})
return drawImg
}
/*
Take the original image and add rectanges on predictions.
Write it to a new file.
*/
const updateImage = (imagePath, img, predictions) => {
// get the filename and replace last occurrence of '.' with '_classified.'
const filename = imagePath.replace(/^.*[\\\/]/, '').replace(/.([^.]*)$/,`_classified_${dataFile}_${confidence * 100.0}.` + '$1')
// get function to draw rect around predicted object
const drawClassDetections = makeDrawClassDetections(predictions);
// draw a rect around predicted object
drawClassDetections(img, getRandomColor);
// write updated image to current directory
cv.imwrite('./' + filename, img)
}
// draw a rect and label in specified area
/**
*
* @param {String} className Predicted class name (identified object)
* @param {Number} confidence The confidence level (ie: .80 = 80%)
* @param {Object} image The image
* @param {Object} rect The rect area
* @param {Object} color The color to use
* @param {Object} [opts={ thickness: 2 }] Options (currently only supports thikness)
*/
const drawRect = (className, confidence, image, rect, color, opts = { thickness: 2 }) => {
let level = Math.round(confidence * 100.0)
image.drawRectangle(
rect,
color,
opts.thickness,
cv.LINE_8
)
// draw the label (className and confidence level)
let label = className + ': ' + level
image.putText(label, new cv.Point2(rect.x, rect.y + 20), cv.FONT_ITALIC, .65, color, 2)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment