Skip to content

Instantly share code, notes, and snippets.

@guimeira
Created December 15, 2017 13:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save guimeira/541e9056364b9491452b7027f12536cc to your computer and use it in GitHub Desktop.
Save guimeira/541e9056364b9491452b7027f12536cc to your computer and use it in GitHub Desktop.
Using mouse to select image region (OpenCV and C++)
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
struct SelectionState {
Point startPt, endPt, mousePos;
bool started = false, done = false;
Rect toRect() {
return Rect (
min(this->startPt.x, this->mousePos.x),
min(this->startPt.y, this->mousePos.y),
abs(this->startPt.x-this->mousePos.x),
abs(this->startPt.y-this->mousePos.y));
}
};
void onMouse(int event, int x, int y, int, void *data) {
SelectionState *state = (SelectionState*) data;
switch(event) {
case EVENT_LBUTTONDOWN:
state->startPt.x = x;
state->startPt.y = y;
state->mousePos.x = x;
state->mousePos.y = y;
state->started = true;
break;
case EVENT_LBUTTONUP:
state->endPt.x = x;
state->endPt.y = y;
state->done = true;
break;
case EVENT_MOUSEMOVE:
state->mousePos.x = x;
state->mousePos.y = y;
break;
}
}
Rect selectRect(Mat image, Scalar color=Scalar(255,0,0), int thickness=2) {
const string window = "rect";
SelectionState state;
namedWindow(window, WINDOW_NORMAL);
setMouseCallback(window, onMouse, &state);
while(!state.done) {
waitKey(100);
if(state.started) {
Mat copy = image.clone();
Rect selection = state.toRect();
rectangle(copy, selection, color, thickness);
imshow(window, copy);
} else {
imshow(window, image);
}
}
return state.toRect();
}
int main(int argc, char *argv[]) {
Mat img = imread("image.png", CV_LOAD_IMAGE_COLOR);
Rect rect = selectRect(img);
cout << "Selected " << rect << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment