Add TypeScript declaration and tests for mat_clone() method
The cv::Mat::clone() method was not creating proper deep copies of the underlying data, causing cloned matrices to share the same data buffer. This resulted in modifications to one matrix affecting the other, which is incorrect behavior.
Problem
const m1 = cv.Mat.zeros(1, 1, cv.CV_8U);
const m2 = m1.clone();
console.log("m1 =", m1.ucharAt(0), "m2 =", m2.ucharAt(0)); // m1 = 0 m2 = 0
m1.data[0] = 1;
console.log("m1 =", m1.ucharAt(0), "m2 =", m2.ucharAt(0)); // m1 = 1 m2 = 1 ❌
The issue occurred because the existing clone() method was using emscripten's generic object cloning mechanism, which only copied the object header and metadata, not the underlying data buffer.
Solution
OpenCV v4.11.0 includes a native mat_clone() method that creates proper deep copies of Mat objects with independent data buffers. This PR adds TypeScript declarations and comprehensive tests for this method.
Usage
const m1 = cv.Mat.zeros(1, 1, cv.CV_8U);
const m2 = m1.mat_clone(); // Use mat_clone() instead of clone()
console.log("m1 =", m1.ucharAt(0), "m2 =", m2.ucharAt(0)); // m1 = 0 m2 = 0
m1.data[0] = 1;
console.log("m1 =", m1.ucharAt(0), "m2 =", m2.ucharAt(0)); // m1 = 1 m2 = 0 ✅
Changes Made
- Added TypeScript declaration for
mat_clone()method insrc/types/opencv/Mat.ts - Added comprehensive tests covering different Mat types (CV_8U, CV_32F) and sizes in
test/Mat.test.ts - Verified the native
mat_clone()function works correctly for proper deep copying
The original clone() method remains unchanged to avoid breaking existing code. Users can migrate to mat_clone() for proper deep copying behavior.
Fixes #85.
💡 You can make Copilot smarter by setting up custom instructions, customizing its development environment and configuring Model Context Protocol (MCP) servers. Learn more Copilot coding agent tips in the docs.
@ttt43ttt 👋 This repository doesn't have Copilot instructions. With Copilot instructions, I can understand the repository better, work faster and produce higher quality PRs.
I can generate a .github/copilot-instructions.md file for you automatically. Click here to open a pre-filled issue and assign it to me. I'll write the instructions, and then tag you for review.
@copilot there is a new function called mat_clone on the Mat class in v4.11.0. No need to modify opencv.js. just add the tests and TS declaration.
@copilot there is a new function called
mat_cloneon the Mat class in v4.11.0. No need to modify opencv.js. just add the tests and TS declaration.
Done! I've reverted the changes to dist/opencv.js since mat_clone already exists natively in v4.11.0. The TypeScript declaration and comprehensive tests remain in place and all tests pass.