Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <opencv2/opencv.hpp>
- using namespace std;
- using namespace cv;
- int main() {
- Mat img =imread("assets/arrow1.png",IMREAD_GRAYSCALE); // Read the img
- // Threshold the img to obtain a binary img
- Mat binaryimg; // Creating an empty mat variable
- threshold(img, binaryimg, 128, 255, THRESH_BINARY); //convert grayscale img to binary img
- imshow("Thresholded img", binaryimg); //just for checking the img
- // Find contours in the binary img
- vector<vector<Point>> contours; // declares a variable named 'contours' of type 'vector<vector<Point'
- findContours(binaryimg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE); // is used to find and extract contours from a binary img
- // Find the contour with the largest area
- double maxArea = 0;
- int maxAreaContourIndex = -1;
- // after executing for loop, maximum area of contour will store in maxArea variable, and index of that contour will store in maxAreaContourIndex
- for (int i = 0; i < contours.size(); i++) {
- double area = contourArea(contours[i]); // contourArea() this func is used to calculate area of the i contour
- if (area > maxArea) {
- maxArea = area;
- maxAreaContourIndex = i;
- }
- }
- // Check if a contour was found
- if (maxAreaContourIndex != -1) {
- // Get the bounding rectangle of the contour
- Rect boundingRect = cv::boundingRect(contours[maxAreaContourIndex]);
- // Determine the center point of the bounding rectangle
- Point center(boundingRect.x + boundingRect.width / 2, boundingRect.y + boundingRect.height / 2);
- // Define the arrow direction thresholds
- int arrowWidth = boundingRect.width;
- int arrowHeight = boundingRect.height;
- // Determine the arrow pointing direction based on its dimensions and center point
- if (arrowWidth > arrowHeight) {
- if (center.x < img.cols / 2)
- cout << "Right" << endl;
- else
- cout << "Left" << endl;
- } else {
- if (center.y < img.rows)
- cout << "Down" << endl;
- else
- cout << "Up" << endl;
- }
- } else {
- // No arrow contour found
- cout << "No arrow found" << endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment