automatic hue threshold

asked 2018-06-02 04:01:08 -0500

alsada gravatar image

updated 2018-06-02 05:45:19 -0500

LBerger gravatar image

I am new in opencv c++ and I wrote the code below to detect red color in real time video, but my teacher asked me to do automatic threshold with (hsv by using h) he did accept this code .please any help or advice will be appreciated.

#include "opencv2/opencv.hpp"
#include <iostream>
#include <termios.h>
using namespace std;
using namespace cv;


int main(){
  VideoCapture cap(0); 
  if(!cap.isOpened()){
    cout << "Error opening video stream or file" << endl;
    return -1;

  }  
  while(1){
    Mat frame;
    cap >> frame;
    if (frame.empty())
      break;
    Mat hsv;
    cvtColor(frame, hsv, COLOR_BGR2HSV);
    Mat1b mask1, mask2;
    inRange(hsv, Scalar(0, 140, 140), Scalar(10, 255, 255), mask1);
    inRange(hsv, Scalar(170, 140, 140), Scalar(180, 255, 255), mask2);


    Mat mask = mask1 | mask2;

        Moments oMoments = moments(mask);

        double moment01 = oMoments.m01;
        double moment10 = oMoments.m10;
        double area = oMoments.m00;

        int posX = moment10/area;
        int posY = moment01/area;


        printf("position (%d,%d)\n", posX, posY);
        imshow("Mask", mask);
        char c=(char)waitKey(25);
    if(c==27)
      break;
  }
  cap.release();
  destroyAllWindows();   
  return 0;
}
edit retag flag offensive close merge delete

Comments

What is tag Alsada1 ?

"he did accept this code " I don't understand your question :

LBerger gravatar imageLBerger ( 2018-06-02 04:20:51 -0500 )edit
1

@LBerger, he did not knew, what to write there, so he made his own tag ;)

and it probably means: the teacher would accept it, if there was an automatic threshold on the H channel used.

@alsada, what was the exact assignment ? "find the red ball" ? if so, you solved it perfectly, and your teachers idea does not make any sense.

automatic threshold on H would be something like this:

Mat H, mask;
extractChannel(hsv,H,0);
double t = threshold(H,mask,0,255,THRESH_OTSU);

for the opencv logo above, t==75, halfway between 0 and 180 (the H spectrum), again a useless value, if you're out to find RED.

berak gravatar imageberak ( 2018-06-02 05:05:17 -0500 )edit

@LBerger,thank you very much,the assignment was to find the red color in video by using only H channel and automatic threshold ,( tag Alsada1) i wrote this mistakenly .my teacher did not accept this part of the code Mat hsv; cvtColor(frame, hsv, COLOR_BGR2HSV); Mat1b mask1, mask2; inRange(hsv, Scalar(0, 140, 140), Scalar(10, 255, 255), mask1); inRange(hsv, Scalar(170, 140, 140), Scalar(180, 255, 255), mask2);

Mat mask = mask1 | mask2;
alsada gravatar imagealsada ( 2018-06-03 06:32:13 -0500 )edit