Opencv.js copyTo freezes

I’ve loaded an image into openCV (the Javascript build) like this:

let src = cv.imread('canvas_input');

I’m able to take a rectangular region from the image like this:

let rect = new cv.Rect(0, 0, 100, 100);
sample = dst.roi(rect);

but when I try to copy that back to the src execution freezes (the next line which logs to console never executes):

sample.copyTo(src_copy, rect);

link to codepen (click the ‘Try it’ button)

What am I missing?

nice, that you have that codepen thing, however, could you please put a more complete code snippet to reproduce it here ?

e.g.what are dst, src_copy ? how do those get initialized ?

Yes, certainly.

with the following HTML:

<canvas id='canvas_input'></canvas>
<canvas id='canvas_output'></canvas>
<canvas id='canvas_output_rect'></canvas>

and the following script:

let canvas = document.getElementById('canvas_input');
load_image_to_canvas('', 'canvas_input');

let src = cv.imread('canvas_input');
let dst = new cv.Mat();
cv.cvtColor(src, src, cv.COLOR_RGBA2RGB, 0);

let ksize = new cv.Size(3, 3);
cv.GaussianBlur(src, dst, ksize, 3, 3, cv.BORDER_DEFAULT);
cv.imshow('canvas_output', dst);

let src_copy = src.clone();
let sample = new cv.Mat();
let rect = new cv.Rect(0, 0, 100, 100);
sample = dst.roi(rect);

console.log('about to copy')
sample.copyTo(src_copy, rect);
cv.imshow('canvas_output_rect', src_copy);

You should be able to reproduce it (I am using the build from


problem is here:

you cannot copy to a Rect, destination needs to be (part of) an image / Mat
(with the same size as sample)

you should also get an error like:

BindingError: Cannot pass "[object Object]" as a Mat


btw, just curious:

how would i use that ?

thank you.

Is there a better way of copying a Rect to a matrix of a certain dimension, without having to write two for loops and setting the pixel values manually?
Ie in Python you can use the slicing syntax to do it in one line, like this.

I initialized the WASM file like this:
var Module = {
wasmBinaryFile: ‘’,
_main: function() { console.log(‘ready’); }
and also added a script src to opencv.js

i think you wanted


(since src_copy is larger than sample, you need to specify a roi, too)
(2nd arg for copyTo() would be a mask image, not a rect)

that worked, thank you