summaryrefslogtreecommitdiff
path: root/crop.cc
blob: 8f570e895ce0931a1575c80eee975fd795d54641 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>
#include <vector>

#include "opencv2/opencv.hpp"

using namespace std;
using namespace cv;

Mat src, img, roi;
Rect crop_rect(0,0,0,0);
vector<cv::Point> pt;
const char* win_name="crop";

void
show_img ()
{
  img = src.clone();
  if(crop_rect.width > 0 && crop_rect.height > 0){
    roi = src(crop_rect);
    cout << crop_rect.width << " " << crop_rect.height << endl;
    imshow("cropped", roi);
  }

  //rectangle(img, crop_rect, Scalar(0,255,0), 1, 8, 0 );
  imshow(win_name,img);
}

void
mouse_handler (int event, int x, int y, int f, void*)
{
  switch (event)
  {
    case CV_EVENT_LBUTTONDOWN:
      circle(src, Point(x,y), 4, 0);
      pt.push_back(cv::Point(x,y));
      show_img();
      break;
  }

  if (pt.size() == 2) {
    //circle(src, Point(pt[1].x, pt[0].y), 4, 0);
    //circle(src, Point(pt[0].x, pt[1].y), 4, 0);
    crop_rect = Rect(pt[0], pt[1]);
    show_img();
  }
}

int
main (int argc, char** argv)
{
  namedWindow(win_name, WINDOW_NORMAL);
  namedWindow("cropped", WINDOW_NORMAL);
  setMouseCallback(win_name, mouse_handler, NULL);

  for (size_t i=1; i<argc; i++) {
    string imgn(argv[i]);
    src=imread(argv[i],1);
    //destroyWindow(win_name);
    destroyWindow("cropped");
    crop_rect.x = 0;
    crop_rect.y = 0;
    crop_rect.height = 0;
    crop_rect.width = 0;
    pt.clear();

    imshow(win_name,src);

    while(1){
      char c=waitKey();
      if(c == 's' && roi.data){
        imshow(win_name, src);
        roi=src(crop_rect);
        imwrite(imgn+"-crop.jpg", roi);
        cout << " saved " << imgn <<endl;
        break;
      }

      if(c==27) break;

      show_img();
    }
  }

  return 0;
}