0
0
mirror of https://github.com/opencv/opencv.git synced 2026-01-18 17:21:42 +01:00

Merge pull request #28216 from happy-capybara-man:4.x

js: restore deep copy behavior for Mat.clone() #28216

### Problem
In OpenCV.js, `cv.Mat.clone()` may resolve to Embind `ClassHandle.clone()` (handle/shallow clone) instead of OpenCV deep copy.

### Changes
- modules/js/src/helpers.js: override `cv.Mat.prototype.clone` -> `mat_clone` after runtime init
- modules/js/test/test_mat.js: update/extend tests to validate deep copy semantics of `clone()`

Fixes  #27572
Related: PR #26643 (js_clone_fix), PR #27985 (documentation update)

### Verification
- Built OpenCV.js with Emscripten 2.0.10
- QUnit: bin/tests.html
- CoreMat: test_mat_creation (0 failures)
<img width="745" height="362" alt="clone_fix" src="https://github.com/user-attachments/assets/16399abf-b94c-4591-b4aa-6e0fbd6cf23b" />

### Pull Request Readiness Checklist

See details at https://github.com/opencv/opencv/wiki/How_to_contribute#making-a-good-pull-request

- [x] I agree to contribute to the project under Apache 2 License.
- [x] To the best of my knowledge, the proposed patch is not based on a code under GPL or another license that is incompatible with OpenCV
- [x] The PR is proposed to the proper branch
- [x] There is a reference to the original bug report and related work
- [x] There is accuracy test, performance test and test data in opencv_extra repository, if applicable
      Patch to opencv_extra has the same branch name.
- [ ] The feature is well documented and sample code can be built with the project CMake
This commit is contained in:
Alexander Smorkalov
2025-12-22 14:30:10 +03:00
committed by GitHub
2 changed files with 17 additions and 1 deletions

View File

@@ -410,3 +410,19 @@ if (
if (cv.UMat) cv.UMat.prototype[Symbol.dispose] = cv.UMat.prototype.delete;
// Add more as OpenCV gains new manual-cleanup classes
}
// Override Emscripten's shallow clone() with OpenCV's deep copy mat_clone()
// This restores the expected behavior where clone() performs a deep copy.
// Background: Emscripten 3.1.71+ added ClassHandle.clone() which only does shallow copy.
// See: https://github.com/opencv/opencv/pull/26643
// See: https://github.com/opencv/opencv/issues/27572
var _opencv_onRuntimeInitialized_backup = Module['onRuntimeInitialized'];
Module['onRuntimeInitialized'] = function() {
if (_opencv_onRuntimeInitialized_backup) {
_opencv_onRuntimeInitialized_backup();
}
if (typeof cv !== 'undefined' && cv.Mat &&
typeof cv.Mat.prototype.mat_clone === 'function') {
cv.Mat.prototype.clone = cv.Mat.prototype.mat_clone;
}
};

View File

@@ -173,7 +173,7 @@ QUnit.test('test_mat_creation', function(assert) {
// clone
{
let mat = cv.Mat.ones(5, 5, cv.CV_8UC1);
let mat2 = mat.mat_clone();
let mat2 = mat.clone();
assert.equal(mat.channels, mat2.channels);
assert.equal(mat.size().height, mat2.size().height);