bazar  1.3.1
tri.cpp
Go to the documentation of this file.
1 
4 #include <cv.h>
5 
6 static const bool no_clipping=false;
7 
8 static int edge_pair(IplImage *im, int sum[], int _a[2], int _b[2], int _c[2], int _d[2])
9 {
10  int a[2];
11  int b[2];
12  int c[2];
13  int d[2];
14 
15  if (_a[1] > _b[1]) {
16  b[0] = _a[0];
17  b[1] = _a[1];
18  a[0] = _b[0];
19  a[1] = _b[1];
20  } else {
21  a[0] = _a[0];
22  a[1] = _a[1];
23  b[0] = _b[0];
24  b[1] = _b[1];
25  }
26 
27  if (_c[1] > _d[1]) {
28  d[0] = _c[0];
29  d[1] = _c[1];
30  c[0] = _d[0];
31  c[1] = _d[1];
32  } else {
33  c[0] = _c[0];
34  c[1] = _c[1];
35  d[0] = _d[0];
36  d[1] = _d[1];
37  }
38 
39  int y_start = MAX(a[1], c[1]);
40  int y_stop = MIN(b[1], d[1]);
41 
42  if (y_start >= y_stop) return 0;
43 
44  if (y_start < 0) {
45  if (no_clipping) return 0;
46  y_start = 0;
47  }
48  if (y_stop >= im->height) {
49  if (no_clipping) return 0;
50  y_stop = im->height - 1;
51  }
52 
53  float slope1 = float(b[0] - a[0])/float(b[1]-a[1]);
54  float delta1 = a[0] - slope1*a[1];
55 
56  float slope2 = float(d[0] - c[0])/float(d[1]-c[1]);
57  float delta2 = c[0] - slope2*c[1];
58 
59  int x_step = im->nChannels;
60  assert (im->depth == IPL_DEPTH_8U);
61 
62  int r=0;
63 
64  for (int y = y_start; y<y_stop; ++y) {
65 
66  float fy = (float) y;
67  float x1 = slope1 * fy + delta1;
68  float x2 = slope2 * fy + delta2;
69  float minx = (x1 < x2 ? x1 : x2);
70  int maxx = (int)(x1 > x2 ? x1 : x2);
71  if (maxx < 0) continue;
72  int x_start = (int)minx;
73  if (x_start > im->width) {
74  if (no_clipping) return 0;
75  continue;
76  }
77  if (x_start < 0) {
78  if (no_clipping) return 0;
79  x_start = 0;
80  }
81 
82  if (maxx >= im->width) maxx=im->width-1;
83  int len = maxx-x_start;
84  if (len >0) {
85  r += len;
86  unsigned char *ptr = (unsigned char *)im->imageData + y*im->widthStep + x_start*x_step;
87 
88  if (im->nChannels>1)
89  for (int x=0; x<len; ++x) {
90  for (int c=0;c<im->nChannels;++c) {
91  sum[c] += *ptr++;
92  }
93  }
94  else
95  for (int x=0; x<len; ++x)
96  sum[0] += *ptr++;
97  }
98  }
99  return r;
100 }
101 
114 int stat_triangle(IplImage *im, int pts[3][2], float avg[3])
115 {
116  int sum[3] = {0,0,0};
117  // for every edge pair...
118  int a = edge_pair(im, sum, pts[0], pts[1], pts[0], pts[2]);
119  int b = edge_pair(im, sum, pts[0], pts[1], pts[1], pts[2]);
120  int c = edge_pair(im, sum, pts[1], pts[2], pts[0], pts[2]);
121  int tot = a+b+c;
122  if (no_clipping) {
123  if (a==0 || b==0 || c==0) tot=0;
124  }
125  if (tot>0) {
126  float ftot = (float)tot;
127  avg[0] = float(sum[0])/ftot;
128  avg[1] = float(sum[1])/ftot;
129  avg[2] = float(sum[2])/ftot;
130  } else {
131  avg[0] = avg[1] = avg[2] = -1;
132  }
133  if (im->nChannels==1) {
134  avg[1] = avg[2] = -1;
135  }
136  return tot;
137 }
138