Skip to content

Instantly share code, notes, and snippets.

@dchun
Created July 7, 2016 16:33
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dchun/4d984680822f483721e7a7ee251cfc38 to your computer and use it in GitHub Desktop.
Save dchun/4d984680822f483721e7a7ee251cfc38 to your computer and use it in GitHub Desktop.
const http = require('http');
const fs = require('fs');
const url = require('url');
const cv = require('opencv');
const server = http.createServer( (req, res) => {
var request = url.parse(req.url, true);
var action = request.pathname;
if (action == '/copy.png') {
var img = fs.readFileSync('./copy.png');
res.writeHead(200, {'Content-Type': 'image/png' });
res.end(img, 'binary');
} else {
res.writeHead(200, {'Content-Type': 'text/html'});
countColonies(res);
res.end();
}
});
function countColonies(res) {
cv.readImage('./private/imgs/7.jpg', function(err, im) {
if (err) reject(err);
im = im.copy();
// store the dimensions in variables for later processing
var width = im.width();
var height = im.height();
if (width < 1 || height < 1) throw new Error('Image has no size');
// set the width of the image to 1000 pixels
nw = 1000;
// maintain pixel ratio of image
nh = (height / width) * nw;
// resize image to create standard variables for sizes of
// colonies to detect later
im.resize(nw,nh);
// copy resized image and store it in a variableto later draw
// circles around colonies for visualization
var copied = im.copy();
// apply gaussian blur
im.gaussianBlur([11,11]);
// apply canny filter
im.canny(50, 125);
var contours = im.findContours();
var colonyCount = 0;
// only draw and count found contours within range of deinfed length
for(i = 0; i < contours.size(); i++) {
if(contours.arcLength(i, true) < 100) {
// draw contours for each found contour and color green
copied.drawContour(contours, i, [0, 255, 0], 3);
colonyCount += 1;
}
}
copied.save('./copy.png');
res.write('<div>'
+ '<h1>'+colonyCount+'</h1>'
+ '<img src="./copy.png" width="500"/>'
+ '</div>'
);
});
}
server.listen(8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment