From 3f1e7fcb8f9d29e19eb10a48dc2b17c6f4080c4a Mon Sep 17 00:00:00 2001 From: Skreg <85214856+shyama7004@users.noreply.github.com> Date: Mon, 3 Mar 2025 17:42:18 +0530 Subject: [PATCH] Merge pull request #26996 from shyama7004:outofBound Fix Logical defect in FilterSpecklesImpl #26996 Fixes : #24963 ### 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 - [ ] 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 --- modules/calib3d/src/stereosgbm.cpp | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/modules/calib3d/src/stereosgbm.cpp b/modules/calib3d/src/stereosgbm.cpp index 75f6f32564..d2fa18e669 100644 --- a/modules/calib3d/src/stereosgbm.cpp +++ b/modules/calib3d/src/stereosgbm.cpp @@ -2345,21 +2345,33 @@ void filterSpecklesImpl(cv::Mat& img, int newVal, int maxSpeckleSize, int maxDif using namespace cv; int width = img.cols, height = img.rows, npixels = width*height; - size_t bufSize = npixels*(int)(sizeof(Point2s) + sizeof(int) + sizeof(uchar)); + // space allocation for: + // labels : npixels * sizeof(int) + // wbuf : npixels * sizeof(Point2s) + // rtype : (npixels + 1) * sizeof(uchar) + size_t bufSize = npixels * sizeof(int) // for labels + + npixels * sizeof(Point2s) // for wavefront buffer (wbuf) + + (npixels + 1) * sizeof(uchar); // for region type (rtype) if( !_buf.isContinuous() || _buf.empty() || _buf.cols*_buf.rows*_buf.elemSize() < bufSize ) _buf.reserveBuffer(bufSize); uchar* buf = _buf.ptr(); int i, j, dstep = (int)(img.step/sizeof(T)); + + // store labels and their corresponding region types int* labels = (int*)buf; buf += npixels*sizeof(labels[0]); + // store wavefront Point2s* wbuf = (Point2s*)buf; buf += npixels*sizeof(wbuf[0]); + // store region type uchar* rtype = (uchar*)buf; + buf += (npixels + 1) * sizeof(rtype[0]); int curlabel = 0; - // clear out label assignments + // clear out label and rtype buffers memset(labels, 0, npixels*sizeof(labels[0])); + memset(rtype, 0, (npixels + 1)*sizeof(rtype[0])); for( i = 0; i < height; i++ ) {