코드

#include <opencv2/opencv.hpp>

#include <opencv2/highgui.hpp>


using namespace cv;

using namespace std;



bool ldown = false, lup = false;

Mat img, gray_img;

Point corner1, corner2;

Rect box;


void Canny_edge(Mat img);


static void mouse_callback(int event, int x, int y, int, void* param) {


if (event == EVENT_LBUTTONDOWN) {

ldown = true;

corner1.x = x;

corner1.y = y;

}


if (event == EVENT_LBUTTONUP) {

if (abs(x - corner1.x) > 20 && abs(y - corner1.y) > 20) {

lup = true;

corner2.x = x;

corner2.y = y;

}

else {

ldown = false;

}

}


if (ldown == true && lup == false) {

Point pt;

pt.x = x;

pt.y = y;


Mat locale_img = img.clone();


rectangle(locale_img, corner1, pt, Scalar(255, 0, 0));

imshow("Original IMG", locale_img);

}


if (ldown == true && lup == true) {

box.width = abs(corner1.x - corner2.x);

box.height = abs(corner1.y - corner2.y);


box.x = min(corner1.x, corner2.x);

box.y = min(corner1.y, corner2.y);


Mat crop(gray_img, box);

Canny_edge(crop);


ldown = false; lup = false;

}

}


void Canny_edge(Mat img) {

Mat contours;

Canny(img, contours, 50, 100);

imshow("Canny_edge", contours);


Mat contoursInv;

threshold(contours, contoursInv, 128, 255, THRESH_BINARY_INV);

imshow("Canny_edge_INV", contoursInv);

}


int main(int args, char *argv[]) {


img = imread("image/flower.jpg", CV_LOAD_IMAGE_COLOR);;

if (!img.data) {

cout << "Image Can't Load" << endl;

return -1;

}


cvtColor(img, gray_img, CV_BGR2GRAY);

imshow("Gray_img", gray_img);


namedWindow("Original IMG");

imshow("Original IMG", img);

setMouseCallback("Original IMG", mouse_callback);

waitKey(0);

}


결과값


+ Recent posts