If you always use cv::findContours with cv::RETR_EXTERNAL and cv::CHAIN_APPROX_SIMPLE, the orientation of the contours is still not guaranteed to be consistently clockwise or counter-clockwise. Here’s why:
1. Contour Orientation in findContours
- OpenCV does not enforce a fixed orientation for contours extracted via
findContours.
- The orientation depends on the shape of the object and the algorithm's internal processing (e.g., how pixels are traversed during contour tracing).
- For simple convex shapes, contours are often counter-clockwise, but this is not a strict rule.
2. Empirical Observations
- For external contours (
RETR_EXTERNAL), OpenCV tends to return contours in counter-clockwise order for most cases, but this is not documented as a guarantee.
- For hole contours (
RETR_TREE or RETR_CCOMP), holes are typically clockwise, but again, this is not strictly enforced.
3. How to Ensure Consistent Orientation
If you need a specific orientation (e.g., always counter-clockwise), you can:
4. Example in C++
#include <opencv2/opencv.hpp>
#include <vector>
int main() {
cv::Mat mask = cv::imread("binary_image.png", cv::IMREAD_GRAYSCALE);
std::vector<std::vector<cv::Point>> contours;
cv::findContours(mask, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_SIMPLE);
// Ensure all contours are counter-clockwise
for (auto& contour : contours) {
double area = cv::contourArea(contour);
if (area < 0) {
std::reverse(contour.begin(), contour.end());
}
}
return 0;
}
Conclusion
findContours with RETR_EXTERNAL does not guarantee a fixed orientation, though it often returns counter-clockwise contours.
- Always verify and correct orientation if your application requires consistency (e.g., for polygon filling, shape matching, or convex hull operations).
Would you like a deeper explanation of how OpenCV traces contours internally?