Skip to content
This repository was archived by the owner on Aug 15, 2019. It is now read-only.

Make sure tf.fromPixels() gets called after the DOM is ready #1064

Merged
merged 5 commits into from
May 28, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 20 additions & 8 deletions src/kernels/backend_webgl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export interface WebGLTimingInfo extends TimingInfo {
export class MathBackendWebGL implements KernelBackend {
private texData = new WeakMap<DataId, TextureData>();
private canvas: HTMLCanvasElement;
private fromPixelsCanvas: HTMLCanvasElement;

private programTimersStack: TimerNode[];
private activeTimers: TimerNode[];
Expand Down Expand Up @@ -119,16 +120,24 @@ export class MathBackendWebGL implements KernelBackend {
const outShape = [pixels.height, pixels.width, numChannels];

if (pixels instanceof HTMLVideoElement) {
if (this.canvas == null) {
throw new Error(
'Can\'t read pixels from HTMLImageElement outside ' +
'the browser.');
if (this.fromPixelsCanvas == null) {
if (typeof document === 'undefined') {
throw new Error(
'Can\'t read pixels from HTMLImageElement outside the browser.');
}
if (document.readyState !== 'complete') {
throw new Error(
'The DOM is not ready yet. Please call tf.fromPixels() ' +
'once the DOM is ready. One way to do that is to add an event ' +
'listener for `DOMContentLoaded` on the document object');
}
this.fromPixelsCanvas = document.createElement('canvas');
}
this.canvas.width = pixels.width;
this.canvas.height = pixels.height;
this.canvas.getContext('2d').drawImage(
this.fromPixelsCanvas.width = pixels.width;
this.fromPixelsCanvas.height = pixels.height;
this.fromPixelsCanvas.getContext('2d').drawImage(
pixels, 0, 0, pixels.width, pixels.height);
pixels = this.canvas;
pixels = this.fromPixelsCanvas;
}
const tempPixelArray = Tensor.make(texShape, {}, 'int32');

Expand Down Expand Up @@ -1017,6 +1026,9 @@ export class MathBackendWebGL implements KernelBackend {
}
this.textureManager.dispose();
this.canvas.remove();
if (this.fromPixelsCanvas != null) {
this.fromPixelsCanvas.remove();
}
if (this.gpgpuCreatedLocally) {
this.gpgpu.dispose();
}
Expand Down