Skip to content

Instantly share code, notes, and snippets.

@kedevked
Created February 17, 2021 22:30
Show Gist options
  • Save kedevked/4138ae9e7d0770d949df2e193db51535 to your computer and use it in GitHub Desktop.
Save kedevked/4138ae9e7d0770d949df2e193db51535 to your computer and use it in GitHub Desktop.
drawing a heart using tensorflow.js
<head>
<style>
body {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
canvas {
width: 100vh;
position: absolute;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
</head>
<body>
<script>
class Heart {
variableNames = ["X"];
outputShape;
userCode;
constructor(shape) {
this.outputShape = shape;
const [h, w] = shape;
this.userCode = `
void main() {
ivec3 coords = getOutputCoords();
float x = float(-coords[0]) + float(${h}) / 2.0;
float y = float(-coords[1]) + float(${w}) / 2.0;
float a = 100.0;
float val = (x*x + y*y - a*a) * (x*x + y*y - a*a) * (x*x + y*y - a*a) - x*x*x*y*y*a;
int r = coords[0];
int c = coords[1];
int d = coords[2];
if(val <= 0.0) {
if (d == 3) {
setOutput(100.0);
} else {
setOutput(255.0);
}
} else {
setOutput(getX(r, c, d));
}
}
`;
}
}
const img = new Image()
img.src = "image.jpg"
img.onload = () => {
const tensor = tf.image.resizeNearestNeighbor(tf.browser.fromPixels(img, 4), [300, 400]);
const tensor1 = tf.ones([300, 400, 3]).cast('int32');
/////////////////
const prog = new Heart(tensor.shape);
const drawn = tf.backend().compileAndRun(prog, [tensor1])
const canvas1 = document.createElement('canvas');
tf.browser.toPixels(tensor, canvas1);
document.body.append(canvas1);
const canvas2 = document.createElement('canvas');
tf.browser.toPixels(drawn, canvas2);
document.body.append(canvas2);
}
const tensor = tf.ones([300, 400, 3], 'int32');
const prog = new Heart(tensor.shape);
const drawn = tf.backend().compileAndRun(prog, [tensor]);
const canvas1 = document.createElement('canvas')
tf.browser.toPixels(drawn, canvas1);
document.body.append(canvas1)
</script>
</body>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment