如何用ObjC++从vector<cv::Point>点列表中提取四个角点?
Extracting Specific Corner Points from
vector<cv::Point> in Objective-C++ I see you're trying to pull out four specific corner points from your given vector<cv::Point> list, and your previous attempts didn't work out. Let's break this down with a clear, tailored solution for Objective-C++.
First, let's recap your requirements:
- From the point list
[(5,10), (15,25), (40,30), (10,15)] - Extract
topLeft = (5,10),topRight = (10,15),bottomLeft = (15,25),bottomRight = (40,30)
The key here is to leverage the coordinate characteristics of each corner:
- The two top points have smaller y-values, split them by x (smaller x = topLeft, larger x = topRight)
- The two bottom points have larger y-values, split them by x (smaller x = bottomLeft, larger x = bottomRight)
Here's the complete Objective-C++ implementation:
#import <Foundation/Foundation.h> #include <opencv2/opencv.hpp> #include <algorithm> using namespace cv; int main(int argc, const char * argv[]) { @autoreleasepool { // Initialize your point list std::vector<Point> points = { Point(5,10), Point(15,25), Point(40,30), Point(10,15) }; // Step 1: Sort points by y-coordinate ascending (smallest y first) std::sort(points.begin(), points.end(), [](const Point& a, const Point& b) { return a.y < b.y; }); // Split into top (first 2 points) and bottom (last 2 points) groups std::vector<Point> topPoints(points.begin(), points.begin() + 2); std::vector<Point> bottomPoints(points.begin() + 2, points.end()); // Step 2: Sort top group by x-coordinate to get topLeft and topRight std::sort(topPoints.begin(), topPoints.end(), [](const Point& a, const Point& b) { return a.x < b.x; }); Point topLeft = topPoints[0]; Point topRight = topPoints[1]; // Step 3: Sort bottom group by x-coordinate to get bottomLeft and bottomRight std::sort(bottomPoints.begin(), bottomPoints.end(), [](const Point& a, const Point& b) { return a.x < b.x; }); Point bottomLeft = bottomPoints[0]; Point bottomRight = bottomPoints[1]; // Verify the results NSLog(@"Extracted Corner Points:"); NSLog(@"topLeft: (%d, %d)", topLeft.x, topLeft.y); NSLog(@"topRight: (%d, %d)", topRight.x, topRight.y); NSLog(@"bottomLeft: (%d, %d)", bottomLeft.x, bottomLeft.y); NSLog(@"bottomRight: (%d, %d)", bottomRight.x, bottomRight.y); } return 0; }
Notes:
- This approach assumes your input always has exactly 4 points (which matches your scenario). If you need to handle variable point counts (e.g., a contour with more points), you'd need to add checks like filtering outliers or using OpenCV's
boundingRect/minAreaRectfunctions—though those would return axis-aligned or rotated rectangles, which might not match your exact desired points. - The lambda functions in
std::sortwork seamlessly in Objective-C++ since it supports mixing C++ and Objective-C syntax. - Make sure your project is set up for Objective-C++ (rename your
.mfile to.mmif needed) and has the OpenCV framework linked.
内容的提问来源于stack exchange,提问作者user9507127
相关产品推荐
相关产品推荐

