Detect touch on OpenCV C++ window - c++

I'm trying to open web-cam video and then pause it on first tap and then close it on second tap on a touchscreen display. I'm using OpenCV version 3.4.0.
Currently I can do it by either pressing q key or by closing window but I am unable to do it with screen tap. Here is my code sample:
bool exit_flag = false;
do
{
cv::imshow("window", draw_frame);
int key = cv::waitKey(3);
if (key == 'q'|| cv::getWindowProperty("window", cv::WND_PROP_ASPECT_RATIO) < 0)
{
//do_something
exit_flag = true;
}
} while (!exit_flag);
cv::waitKey(0);
cv::destroyWindow("window");
I tried using cv::EVENT_LBUTTONDOWN but couldn't use it properly to bring any positive results.
Pardon me if code isn't proper, I have created a sample for demonstration and I'm not very good at C++.

If you want to close your imshow window using mouse, you can simply use setMouseCallback. Here is my approach: you can close your window by "q" keyword or by simply clicking to window:
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace std;
using namespace cv;
static bool exit_flag = false;
static void mouseHandler(int event,int x,int y, int flags,void* param){
if(event==1)
exit_flag = true;
}
int main(int argc, char **argv) {
Mat draw_frame = imread("/ur/image/directory/photo.jpg");
do {
cv::imshow("window", draw_frame);
int key = cv::waitKey(3);
setMouseCallback("window",mouseHandler);
if (key == 'q'|| cv::getWindowProperty("window", cv::WND_PROP_ASPECT_RATIO) < 0)
{
//do_something
exit_flag = true;
}
} while (!exit_flag);
cv::destroyWindow("window");
}

Related

How to use a GUI generated window with command line terminal in background?

Here is the main file of the game snake I am developing. It uses OpenGL and ncurses. Everything runs exactly like I want it too, but I can only input my key presses to play the game if my command line terminal is the top level process of my computer. Currently, when I run the program, the OpenGL window spawns ontop of my command line prompt and then I need to re select my command line prompt and bring it to the front to play my game.
I want my terminal to recognize my key presses when the terminal is behind the openGL window. How do I do this if it is possible? I am using Ubuntu Linux.
#include <chrono>
#include <thread>
#include <unistd.h>
#include <ncurses.h>
#include "Snake.h"
#include <GL/glut.h>
int khbit(void)
{
int ch = getch();
if (ch != ERR)
{
ungetch(ch);
return 1;
}
else
{
return 0;
}
}
int main(int argc, char **argv)
{
std::unique_ptr<GameBoxes::Box> squareBackground(new GameBoxes::Box(std::stoi(argv[1]), std::stoi(argv[2]),
std::stoi(argv[3]), std::stoi(argv[4])));
int cArgs[4];
(*squareBackground).getSizeArray(cArgs);
glutInit(&argc, argv);
(*squareBackground).createBackGroundTexture();
glClear(GL_COLOR_BUFFER_BIT); //new
// initialize random seed:
srand (time(NULL));
// start ncurses
initscr();
// Line buffering disabled
cbreak();
// Don't echo while we do getch
noecho();
// Allows checking for Keypress
nodelay(stdscr, TRUE);
scrollok(stdscr, TRUE);
bool play = true;
while (play == true)
{
bool alive = true;
std::unique_ptr<GameBoxes::Snake> snake(new GameBoxes::Snake(*squareBackground, cArgs)); //new
int direction;
char directionTwo = 't';
flushinp();
while (alive == true)
{
if (khbit())
{
direction = getch();
directionTwo = direction;
alive = (*snake).moveSnake(*squareBackground, direction, cArgs); // Grow into a loop
flushinp();
}
else
{
alive = (*snake).moveSnake(*squareBackground, directionTwo, cArgs); // Grow into a loop
}
if (direction == 'k')
{
endwin();
return 0;
}
std::chrono::milliseconds dura( 40);
std::this_thread::sleep_for( dura );
}
}
glutMainLoop();
return 0;
}

OpenCV 3.0.0 with XCode 6.0 simple code works using putText doesn't

Coming from a Windows world, I'm quite new to the OS X environment. I have created a simple OpenCV project with XCode from scratch to only show a video feed, it works. But I wanted to show my students how to insert text in image with the putText method and it fails to compile. I have added core, videoio and highgui libs to the project.
The following errors occur
Here is the simple code.
#include <iostream>
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui.hpp>
using namespace cv;
using namespace std;
int main(int argc, const char * argv[])
{
Mat img;
VideoCapture capture;
if (!capture.open(0)) {
cout << "Erreur d'ouverture de caméra\n";
return -1;
}
int c = 0;
int result = 0;
bool captureOk = true;
string winName = "Main window";
string testString = "TEST!";
while (c != 27) {
captureOk = capture.read(img);
if (captureOk) {
putText(img, testString, Point(30, 30), FONT_HERSHEY_SIMPLEX, 0.5, Scalar(255));
imshow(winName, img);
}
else {
result = -1;
}
c = waitKey(1);
}
return result;
}
Thanks!

How do I draw lines on a image using mouse clicks in opencv?

So, after following the advise from the stackexchange users about mouse event, I was able to understand and implement some simple task using mouse clicks. So, the next goal was to draw a simple line using the mouse left click and mouse right click. Unfortunately, I can't see any line after I implemented my program.
int x,y;
Point p(0,0);
Point q(0,0);
Mat xal;
void drawimage()
{
a = q.x - p.x; //i am just checking out the values of a and b to see if the drawimagefunction is being called in the rightmouse click event
b = q.y - p.y;
cout<<" a is :"<<a<<endl;
cout<<"b is:"<<b<<endl;
line(xal,Point(p.x,p.y),Point(q.x,q.y),Scalar(0,0,255),2,8);
}
void onMouse( int event, int x, int y, int f, void* )
{
switch (event)
{
case EVENT_LBUTTONDOWN:
cout<<"Left button was pressed"<<x<<" "<<y<<" "<<endl;
{
p.x = x;
p.y = y;
cout<<"p is:"<<p.x<<p.y<<endl;
}
break;
case EVENT_RBUTTONDOWN:
cout<<"Right button was pressed at :"<<x <<" "<<y<<endl;
{
q.x = x;
q.y = y;
drawimage();//no line is being drawn though i can see that i get the values of a and b in the drawimage function.
}
break;
default:
break;
}
}
int main()
{
xal = imread("pic.JPG);
namedWindow("Picture",1);
setMouseCallback("Picture",onMouse,NULL);
imshow("Picture",xal);
cvwaitkey(0);
}
Add the following after your "line(..)" call in your drawLine() function:
imshow("Picture", xal);
The problem is that you are writing the line to the xal matrix, but you have not updated the image on the screen, which is what the imshow(..) call will do.
Try this one code. It is useful for you.
#include "opencv2/highgui/highgui.hpp"
#include <iostream>
using namespace std;
using namespace cv;
void drawimage()
{
line(xal,Point(p->x,p->y),Point(q->x,q->y),Scalar(0,0,255),2,8);
}
void CallBackFunc(int event, int x, int y, int flags, void *ptr )
{
if ( event == EVENT_LBUTTONDOWN )
{
Point*p = (Point*)ptr;
p->x = x;
p->y = y;
drawimage();
}
else if ( event == EVENT_RBUTTONDOWN )
{
Point*q = (Point*)ptr;
q->x = x;
q->y = y;
drawimage();
}
}
int main(int argc, char** argv)
{
// Read image from file
Point p;
Point q;
Mat xal = imread("MyPic.JPG");
//if fail to read the image
if ( xal.empty() )
{
cout << "Error loading the image" << endl;
return -1;
}
//Create a window
namedWindow("My Window", 1);
//set the callback function for any mouse event
setMouseCallback("My Window", CallBackFunc,&p);
setMouseCallback("My Window", CallBackFunc,&q);
//show the image
imshow("My Window", xal);
// Wait until user press some key
waitKey(0);
return 0;
}

XNextEvent Doesn't works for some reason

I'm trying to catch keypress events using XLib. But for some reasons XNextEvent not working.
I'm not receiving any errors, but it looks like my program stuck on the line of "XNextEvent" call.
Here is my code:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;
int main()
{
XEvent event;
KeySym key;
char text[255];
Display *dis;
dis = XOpenDisplay(NULL);
while (1) {
XNextEvent(dis, &event);
if (event.type==KeyPress && XLookupString(&event.xkey,text,255,&key,0) == 1) {
if (text[0]=='q') {
XCloseDisplay(dis);
return 0;
}
printf("You pressed the %c key!\n", text[0]);
}
}
return 0;
}
This is not how X11 windowing system works.
Read this carefully. The key point is :
The source of the event is the viewable window that the pointer is in.
You do not create a window, therefore your program doesn't receive keyboard events. Even if you created window, it has to have focus :
The window used by the X server to report these events depends on the window's position in the window hierarchy and whether any intervening window prohibits the generation of these events.
Working example
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
using namespace std;
int main()
{
XEvent event;
Display *dis;
Window root;
Bool owner_events = False;
unsigned int modifiers = ControlMask | LockMask;
dis = XOpenDisplay(NULL);
root = XDefaultRootWindow(dis);
unsigned int keycode = XKeysymToKeycode(dis, XK_P);
XSelectInput(dis,root, KeyPressMask);
XGrabKey(dis, keycode, modifiers, root, owner_events, GrabModeAsync, GrabModeAsync);
while (1) {
Bool QuiteCycle = False;
XNextEvent(dis, &event);
if (event.type == KeyPress) {
cout << "Hot key pressed!" << endl;
XUngrabKey(dis, keycode, modifiers, root);
QuiteCycle = True;
}
if (QuiteCycle) {
break;
}
}
XCloseDisplay(dis);
return 0;
}

OpenCV - can't get any output from camera

I am trying to connect my camera with opencv, but window is showing a grey output screen with no image and output window of vc++ is showing the following error:
... 'opencv practice.exe': Loaded 'C:\Windows\SysWOW64\msyuv.dll',
Cannot find or open the PDB file 'opencv practice.exe': Unloaded
'C:\Windows\SysWOW64\msyuv.dll' ...
i tried fining the msyuv.dll, and it is available there.
i have one further question, next to this, i want to implement this on unity3d, so should i stick with opencv or use emgucv?
#include "StdAfx.h"
#include <stdio.h>
#include <stdlib.h>
#include <opencv\cvaux.h>
#include <opencv\highgui.h>
#include <opencv\cxcore.h>
using namespace std;
int main(int argc)
{
CvCapture* cam = NULL;`
cvNamedWindow("hi",CV_WINDOW_AUTOSIZE);
IplImage* img = NULL;
cam = cvCaptureFromCAM(-1);
char a;
while(1)
{
if(cam != NULL)
{
img = cvQueryFrame(cam);
}
else
{
printf("erro1");
return -1;
}
cvShowImage("hi", img);
a = cvWaitKey(20);
if(a == 27)
break;
}
cvReleaseCapture(&cam);
cvDestroyAllWindows();
return 0;
}