suraj0152

Task2

Jul 1st, 2023
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.37 KB | Software | 0 0
  1. #include <iostream>
  2. #include <opencv2/opencv.hpp>
  3.  
  4. using namespace std;
  5. using namespace cv;
  6. int main() {
  7.    
  8.     Mat img =imread("assets/arrow1.png",IMREAD_GRAYSCALE);        // Read the img
  9.    
  10.     // Threshold the img to obtain a binary img
  11.     Mat binaryimg;     // Creating an empty mat variable
  12.     threshold(img, binaryimg, 128, 255, THRESH_BINARY);       //convert grayscale img to binary img
  13.  
  14.     imshow("Thresholded img", binaryimg);        //just for checking the img
  15.  
  16.     // Find contours in the binary img
  17.     vector<vector<Point>> contours;        // declares a variable named 'contours' of type 'vector<vector<Point'
  18.     findContours(binaryimg, contours, RETR_EXTERNAL, CHAIN_APPROX_SIMPLE);       // is used to find and extract contours from a binary img
  19.  
  20.     // Find the contour with the largest area
  21.     double maxArea = 0;
  22.     int maxAreaContourIndex = -1;
  23.  
  24.     // after executing for loop, maximum area of contour will store in maxArea variable, and index of that contour will store in maxAreaContourIndex
  25.     for (int i = 0; i < contours.size(); i++) {
  26.         double area = contourArea(contours[i]);    // contourArea() this func is used to calculate area of the i contour
  27.         if (area > maxArea) {
  28.             maxArea = area;
  29.             maxAreaContourIndex = i;
  30.         }
  31.     }
  32.  
  33.     // Check if a contour was found
  34.     if (maxAreaContourIndex != -1) {
  35.         // Get the bounding rectangle of the contour
  36.         Rect boundingRect = cv::boundingRect(contours[maxAreaContourIndex]);
  37.  
  38.         // Determine the center point of the bounding rectangle
  39.         Point center(boundingRect.x + boundingRect.width / 2, boundingRect.y + boundingRect.height / 2);
  40.  
  41.         // Define the arrow direction thresholds
  42.         int arrowWidth = boundingRect.width;
  43.         int arrowHeight = boundingRect.height;
  44.  
  45.         // Determine the arrow pointing direction based on its dimensions and center point
  46.         if (arrowWidth > arrowHeight) {
  47.             if (center.x < img.cols / 2)
  48.                 cout << "Right" << endl;
  49.             else
  50.                 cout << "Left" << endl;
  51.         } else {
  52.             if (center.y < img.rows)
  53.                 cout << "Down" << endl;
  54.             else
  55.                 cout << "Up" << endl;
  56.         }
  57.     } else {
  58.         // No arrow contour found
  59.         cout << "No arrow found" << endl;
  60.     }
  61.  
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment