objdetect(hog): validate image size in compute() and guard windowsInImage() (#31168)

When HOGDescriptor::compute() is called without explicit locations on an image whose padded dimensions are smaller than winSize, HOGCache::windowsInImage() computes a negative window count along the undersized axis:

If one dimension is smaller than winSize (for example, 16 x 193 with default 64 x 128 winSize), windowsInImage().area() is negative and wraps to a huge size_t in nwindows, causing descriptors.resize(dsize * nwindows) to throw std::length_error (vector<T> too long).
If both dimensions are smaller than winSize, windowsInImage().area() becomes positive ((-w) * (-h)).
If a dimension is 1 to winStride - 1 pixels smaller than winSize, truncating integer division yields (size - winSize) / winStride + 1 == 1 instead of 0.
This commit is contained in:
Hardik K
2026-12-02 17:58:49 +05:30
committed by GitHub
parent cef130bc23
commit 3fef633bcc
2 changed files with 46 additions and 0 deletions

View File

@@ -1147,6 +1147,8 @@ void HOGCache::normalizeBlockHistogram(float* _hist) const
Size HOGCache::windowsInImage(const Size& imageSize, const Size& winStride) const
{
if (imageSize.width < winSize.width || imageSize.height < winSize.height)
return Size(0, 0);
return Size((imageSize.width - winSize.width)/winStride.width + 1,
(imageSize.height - winSize.height)/winStride.height + 1);
}
@@ -1476,6 +1478,12 @@ void HOGDescriptor::compute(InputArray _img, std::vector<float>& descriptors,
padding.height = (int)alignSize(std::max(padding.height, 0), cacheStride.height);
Size paddedImgSize(imgSize.width + padding.width*2, imgSize.height + padding.height*2);
if (!nwindows)
{
CV_CheckGE(paddedImgSize.width, winSize.width, "Image width (including padding) must be at least winSize.width");
CV_CheckGE(paddedImgSize.height, winSize.height, "Image height (including padding) must be at least winSize.height");
}
CV_OCL_RUN(_img.dims() <= 2 && _img.type() == CV_8UC1 && _img.isUMat(),
ocl_compute(_img, winStride, descriptors, HOGDescriptor::DESCR_FORMAT_COL_BY_COL, blockSize,
cellSize, nbins, blockStride, winSize, (float)getWinSigma(), gammaCorrection, L2HysThreshold, signedGradient))
@@ -1547,6 +1555,9 @@ void HOGDescriptor::detect(InputArray _img,
padding.height = (int)alignSize(std::max(padding.height, 0), cacheStride.height);
Size paddedImgSize(img.cols + padding.width*2, img.rows + padding.height*2);
if( !nwindows && (paddedImgSize.width < winSize.width || paddedImgSize.height < winSize.height) )
return;
HOGCache cache(this, img, padding, padding, nwindows == 0, cacheStride);
if( !nwindows )