Skip to content

Commit 3014601

Browse files
authored
[utils] Adds ml5.flipImage() to flip images horizontally (#656)
* adds flipImage to utils * adds p5 utils to flip video
1 parent c7e77cc commit 3014601

File tree

1 file changed

+61
-1
lines changed

1 file changed

+61
-1
lines changed

src/utils/imageUtilities.js

Lines changed: 61 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
// https://opensource.org/licenses/MIT
55

66
import * as tf from '@tensorflow/tfjs';
7+
import p5Utils from './p5Utils';
78

89
// Resize video elements
910
const processVideo = (input, size, callback = () => {}) => {
@@ -61,6 +62,64 @@ const cropImage = (img) => {
6162
return img.slice([beginHeight, beginWidth, 0], [size, size, 3]);
6263
};
6364

65+
const flipImage = (img) => {
66+
// image image, bitmap, or canvas
67+
let imgWidth;
68+
let imgHeight;
69+
let inputImg;
70+
71+
if (img instanceof HTMLImageElement ||
72+
img instanceof HTMLCanvasElement ||
73+
img instanceof HTMLVideoElement ||
74+
img instanceof ImageData) {
75+
inputImg = img;
76+
} else if (typeof img === 'object' &&
77+
(img.elt instanceof HTMLImageElement ||
78+
img.elt instanceof HTMLCanvasElement ||
79+
img.elt instanceof HTMLVideoElement ||
80+
img.elt instanceof ImageData)) {
81+
82+
inputImg = img.elt; // Handle p5.js image
83+
} else if (typeof img === 'object' &&
84+
img.canvas instanceof HTMLCanvasElement) {
85+
inputImg = img.canvas; // Handle p5.js image
86+
} else {
87+
inputImg = img;
88+
}
89+
90+
if (inputImg instanceof HTMLVideoElement) {
91+
// should be videoWidth, videoHeight?
92+
imgWidth = inputImg.width;
93+
imgHeight = inputImg.height;
94+
} else {
95+
imgWidth = inputImg.width;
96+
imgHeight = inputImg.height;
97+
}
98+
99+
100+
if (p5Utils.checkP5()) {
101+
const p5Canvas = p5Utils.p5Instance.createGraphics(imgWidth, imgHeight);
102+
p5Canvas.push()
103+
p5Canvas.translate(imgWidth, 0);
104+
p5Canvas.scale(-1, 1);
105+
p5Canvas.image(img, 0, 0, imgWidth, imgHeight);
106+
p5Canvas.pop()
107+
108+
return p5Canvas;
109+
}
110+
const canvas = document.createElement('canvas');
111+
canvas.width = imgWidth;
112+
canvas.height = imgHeight;
113+
114+
const ctx = canvas.getContext('2d');
115+
ctx.drawImage(inputImg, 0, 0, imgWidth, imgHeight);
116+
ctx.translate(imgWidth, 0);
117+
ctx.scale(-1, 1);
118+
ctx.drawImage(canvas, imgWidth * -1, 0, imgWidth, imgHeight);
119+
return canvas;
120+
121+
}
122+
64123
// Static Method: image to tf tensor
65124
function imgToTensor(input, size = null) {
66125
return tf.tidy(() => {
@@ -79,4 +138,5 @@ export {
79138
processVideo,
80139
cropImage,
81140
imgToTensor,
82-
};
141+
flipImage
142+
};

0 commit comments

Comments
 (0)