4
4
// https://opensource.org/licenses/MIT
5
5
6
6
import * as tf from '@tensorflow/tfjs' ;
7
+ import p5Utils from './p5Utils' ;
7
8
8
9
// Resize video elements
9
10
const processVideo = ( input , size , callback = ( ) => { } ) => {
@@ -61,6 +62,64 @@ const cropImage = (img) => {
61
62
return img . slice ( [ beginHeight , beginWidth , 0 ] , [ size , size , 3 ] ) ;
62
63
} ;
63
64
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
+
64
123
// Static Method: image to tf tensor
65
124
function imgToTensor ( input , size = null ) {
66
125
return tf . tidy ( ( ) => {
@@ -79,4 +138,5 @@ export {
79
138
processVideo ,
80
139
cropImage ,
81
140
imgToTensor ,
82
- } ;
141
+ flipImage
142
+ } ;
0 commit comments