From 7c3880d0deee6f0d4f6e52057e2ade4bade1d92a Mon Sep 17 00:00:00 2001 From: pbkx <93405617+pbkx@users.noreply.github.com> Date: Mon, 7 Sep 2026 21:44:04 -0700 Subject: [PATCH] validate KeyPoint::convert indexes --- modules/core/src/types.cpp | 5 ++-- modules/core/test/test_misc.cpp | 52 +++++++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 3 deletions(-) diff --git a/modules/core/src/types.cpp b/modules/core/src/types.cpp index 8c732df5c7..95af24ac84 100644 --- a/modules/core/src/types.cpp +++ b/modules/core/src/types.cpp @@ -79,12 +79,11 @@ void KeyPoint::convert(const std::vector& keypoints, std::vector= 0 ) + if( idx >= 0 && static_cast(idx) < keypoints.size() ) points2f[i] = keypoints[idx].pt; else { - CV_Error( cv::Error::StsBadArg, "keypointIndexes has element < 0. TODO: process this case" ); - //points2f[i] = Point2f(-1, -1); + CV_Error( cv::Error::StsBadArg, "keypointIndexes has element out of range" ); } } } diff --git a/modules/core/test/test_misc.cpp b/modules/core/test/test_misc.cpp index 1682ff27ea..af0c433195 100644 --- a/modules/core/test/test_misc.cpp +++ b/modules/core/test/test_misc.cpp @@ -950,6 +950,58 @@ TEST(Core_Types, trivially_copyable_extra) } #endif +TEST(Core_KeyPoint, convert_rejects_negative_index) +{ + const std::vector keypoints(1, KeyPoint(1, 2, 1)); + const std::vector indexes(1, -1); + std::vector points; + + EXPECT_THROW(KeyPoint::convert(keypoints, points, indexes), cv::Exception); +} + +TEST(Core_KeyPoint, convert_rejects_index_for_empty_input) +{ + const std::vector keypoints; + const std::vector indexes(1, 0); + std::vector points; + + EXPECT_THROW(KeyPoint::convert(keypoints, points, indexes), cv::Exception); +} + +TEST(Core_KeyPoint, convert_rejects_out_of_range_indexes) +{ + const std::vector keypoints(1, KeyPoint(1, 2, 1)); + std::vector points; + + const int invalidIndexes[] = { 1, 100 }; + for( size_t i = 0; i < sizeof(invalidIndexes) / sizeof(invalidIndexes[0]); i++ ) + { + const std::vector indexes(1, invalidIndexes[i]); + EXPECT_THROW(KeyPoint::convert(keypoints, points, indexes), cv::Exception); + } +} + +TEST(Core_KeyPoint, convert_preserves_index_order_and_duplicates) +{ + const std::vector keypoints = { + KeyPoint(1, 2, 1), KeyPoint(3, 4, 1), KeyPoint(5, 6, 1) + }; + const std::vector indexes = { 2, 0, 2, 1 }; + std::vector points; + + KeyPoint::convert(keypoints, points, indexes); + + const Point2f expected[] = { Point2f(5, 6), Point2f(1, 2), Point2f(5, 6), Point2f(3, 4) }; + ASSERT_EQ(sizeof(expected) / sizeof(expected[0]), points.size()); + for( size_t i = 0; i < points.size(); i++ ) + EXPECT_EQ(expected[i], points[i]); + + KeyPoint::convert(keypoints, points); + ASSERT_EQ(keypoints.size(), points.size()); + for( size_t i = 0; i < points.size(); i++ ) + EXPECT_EQ(keypoints[i].pt, points[i]); +} + template class Rect_Test : public testing::Test {}; TYPED_TEST_CASE_P(Rect_Test);