1 #ifndef _GNU_SOURCE
2 #define _GNU_SOURCE
3 #endif
4 #include "image.h"
5 #include "utils.h"
6 #include "blas.h"
7 #include "dark_cuda.h"
8 #include <stdio.h>
9 #ifndef _USE_MATH_DEFINES
10 #define _USE_MATH_DEFINES
11 #endif
12 #include <math.h>
13 
14 #ifndef STB_IMAGE_IMPLEMENTATION
15 #define STB_IMAGE_IMPLEMENTATION
16 #include "stb_image.h"
17 #endif
18 #ifndef STB_IMAGE_WRITE_IMPLEMENTATION
19 #define STB_IMAGE_WRITE_IMPLEMENTATION
20 #include "stb_image_write.h"
21 #endif
22 
23 extern int check_mistakes;
24 //int windows = 0;
25 
26 float colors[6][3] = { {1,0,1}, {0,0,1},{0,1,1},{0,1,0},{1,1,0},{1,0,0} };
27 
get_color(int c,int x,int max)28 float get_color(int c, int x, int max)
29 {
30     float ratio = ((float)x/max)*5;
31     int i = floor(ratio);
32     int j = ceil(ratio);
33     ratio -= i;
34     float r = (1-ratio) * colors[i][c] + ratio*colors[j][c];
35     //printf("%f\n", r);
36     return r;
37 }
38 
get_pixel(image m,int x,int y,int c)39 static float get_pixel(image m, int x, int y, int c)
40 {
41     assert(x < m.w && y < m.h && c < m.c);
42     return m.data[c*m.h*m.w + y*m.w + x];
43 }
get_pixel_extend(image m,int x,int y,int c)44 static float get_pixel_extend(image m, int x, int y, int c)
45 {
46     if (x < 0 || x >= m.w || y < 0 || y >= m.h) return 0;
47     /*
48     if(x < 0) x = 0;
49     if(x >= m.w) x = m.w-1;
50     if(y < 0) y = 0;
51     if(y >= m.h) y = m.h-1;
52     */
53     if (c < 0 || c >= m.c) return 0;
54     return get_pixel(m, x, y, c);
55 }
set_pixel(image m,int x,int y,int c,float val)56 static void set_pixel(image m, int x, int y, int c, float val)
57 {
58     if (x < 0 || y < 0 || c < 0 || x >= m.w || y >= m.h || c >= m.c) return;
59     assert(x < m.w && y < m.h && c < m.c);
60     m.data[c*m.h*m.w + y*m.w + x] = val;
61 }
add_pixel(image m,int x,int y,int c,float val)62 static void add_pixel(image m, int x, int y, int c, float val)
63 {
64     assert(x < m.w && y < m.h && c < m.c);
65     m.data[c*m.h*m.w + y*m.w + x] += val;
66 }
67 
composite_image(image source,image dest,int dx,int dy)68 void composite_image(image source, image dest, int dx, int dy)
69 {
70     int x,y,k;
71     for(k = 0; k < source.c; ++k){
72         for(y = 0; y < source.h; ++y){
73             for(x = 0; x < source.w; ++x){
74                 float val = get_pixel(source, x, y, k);
75                 float val2 = get_pixel_extend(dest, dx+x, dy+y, k);
76                 set_pixel(dest, dx+x, dy+y, k, val * val2);
77             }
78         }
79     }
80 }
81 
border_image(image a,int border)82 image border_image(image a, int border)
83 {
84     image b = make_image(a.w + 2*border, a.h + 2*border, a.c);
85     int x,y,k;
86     for(k = 0; k < b.c; ++k){
87         for(y = 0; y < b.h; ++y){
88             for(x = 0; x < b.w; ++x){
89                 float val = get_pixel_extend(a, x - border, y - border, k);
90                 if(x - border < 0 || x - border >= a.w || y - border < 0 || y - border >= a.h) val = 1;
91                 set_pixel(b, x, y, k, val);
92             }
93         }
94     }
95     return b;
96 }
97 
tile_images(image a,image b,int dx)98 image tile_images(image a, image b, int dx)
99 {
100     if(a.w == 0) return copy_image(b);
101     image c = make_image(a.w + b.w + dx, (a.h > b.h) ? a.h : b.h, (a.c > b.c) ? a.c : b.c);
102     fill_cpu(c.w*c.h*c.c, 1, c.data, 1);
103     embed_image(a, c, 0, 0);
104     composite_image(b, c, a.w + dx, 0);
105     return c;
106 }
107 
get_label(image ** characters,char * string,int size)108 image get_label(image **characters, char *string, int size)
109 {
110     if(size > 7) size = 7;
111     image label = make_empty_image(0,0,0);
112     while(*string){
113         image l = characters[size][(int)*string];
114         image n = tile_images(label, l, -size - 1 + (size+1)/2);
115         free_image(label);
116         label = n;
117         ++string;
118     }
119     image b = border_image(label, label.h*.25);
120     free_image(label);
121     return b;
122 }
123 
get_label_v3(image ** characters,char * string,int size)124 image get_label_v3(image **characters, char *string, int size)
125 {
126     size = size / 10;
127     if (size > 7) size = 7;
128     image label = make_empty_image(0, 0, 0);
129     while (*string) {
130         image l = characters[size][(int)*string];
131         image n = tile_images(label, l, -size - 1 + (size + 1) / 2);
132         free_image(label);
133         label = n;
134         ++string;
135     }
136     image b = border_image(label, label.h*.05);
137     free_image(label);
138     return b;
139 }
140 
draw_label(image a,int r,int c,image label,const float * rgb)141 void draw_label(image a, int r, int c, image label, const float *rgb)
142 {
143     int w = label.w;
144     int h = label.h;
145     if (r - h >= 0) r = r - h;
146 
147     int i, j, k;
148     for(j = 0; j < h && j + r < a.h; ++j){
149         for(i = 0; i < w && i + c < a.w; ++i){
150             for(k = 0; k < label.c; ++k){
151                 float val = get_pixel(label, i, j, k);
152                 set_pixel(a, i+c, j+r, k, rgb[k] * val);
153             }
154         }
155     }
156 }
157 
draw_box_bw(image a,int x1,int y1,int x2,int y2,float brightness)158 void draw_box_bw(image a, int x1, int y1, int x2, int y2, float brightness)
159 {
160     //normalize_image(a);
161     int i;
162     if (x1 < 0) x1 = 0;
163     if (x1 >= a.w) x1 = a.w - 1;
164     if (x2 < 0) x2 = 0;
165     if (x2 >= a.w) x2 = a.w - 1;
166 
167     if (y1 < 0) y1 = 0;
168     if (y1 >= a.h) y1 = a.h - 1;
169     if (y2 < 0) y2 = 0;
170     if (y2 >= a.h) y2 = a.h - 1;
171 
172     for (i = x1; i <= x2; ++i) {
173         a.data[i + y1*a.w + 0 * a.w*a.h] = brightness;
174         a.data[i + y2*a.w + 0 * a.w*a.h] = brightness;
175     }
176     for (i = y1; i <= y2; ++i) {
177         a.data[x1 + i*a.w + 0 * a.w*a.h] = brightness;
178         a.data[x2 + i*a.w + 0 * a.w*a.h] = brightness;
179     }
180 }
181 
draw_box_width_bw(image a,int x1,int y1,int x2,int y2,int w,float brightness)182 void draw_box_width_bw(image a, int x1, int y1, int x2, int y2, int w, float brightness)
183 {
184     int i;
185     for (i = 0; i < w; ++i) {
186         float alternate_color = (w % 2) ? (brightness) : (1.0 - brightness);
187         draw_box_bw(a, x1 + i, y1 + i, x2 - i, y2 - i, alternate_color);
188     }
189 }
190 
draw_box(image a,int x1,int y1,int x2,int y2,float r,float g,float b)191 void draw_box(image a, int x1, int y1, int x2, int y2, float r, float g, float b)
192 {
193     //normalize_image(a);
194     int i;
195     if(x1 < 0) x1 = 0;
196     if(x1 >= a.w) x1 = a.w-1;
197     if(x2 < 0) x2 = 0;
198     if(x2 >= a.w) x2 = a.w-1;
199 
200     if(y1 < 0) y1 = 0;
201     if(y1 >= a.h) y1 = a.h-1;
202     if(y2 < 0) y2 = 0;
203     if(y2 >= a.h) y2 = a.h-1;
204 
205     for(i = x1; i <= x2; ++i){
206         a.data[i + y1*a.w + 0*a.w*a.h] = r;
207         a.data[i + y2*a.w + 0*a.w*a.h] = r;
208 
209         a.data[i + y1*a.w + 1*a.w*a.h] = g;
210         a.data[i + y2*a.w + 1*a.w*a.h] = g;
211 
212         a.data[i + y1*a.w + 2*a.w*a.h] = b;
213         a.data[i + y2*a.w + 2*a.w*a.h] = b;
214     }
215     for(i = y1; i <= y2; ++i){
216         a.data[x1 + i*a.w + 0*a.w*a.h] = r;
217         a.data[x2 + i*a.w + 0*a.w*a.h] = r;
218 
219         a.data[x1 + i*a.w + 1*a.w*a.h] = g;
220         a.data[x2 + i*a.w + 1*a.w*a.h] = g;
221 
222         a.data[x1 + i*a.w + 2*a.w*a.h] = b;
223         a.data[x2 + i*a.w + 2*a.w*a.h] = b;
224     }
225 }
226 
draw_box_width(image a,int x1,int y1,int x2,int y2,int w,float r,float g,float b)227 void draw_box_width(image a, int x1, int y1, int x2, int y2, int w, float r, float g, float b)
228 {
229     int i;
230     for(i = 0; i < w; ++i){
231         draw_box(a, x1+i, y1+i, x2-i, y2-i, r, g, b);
232     }
233 }
234 
draw_bbox(image a,box bbox,int w,float r,float g,float b)235 void draw_bbox(image a, box bbox, int w, float r, float g, float b)
236 {
237     int left  = (bbox.x-bbox.w/2)*a.w;
238     int right = (bbox.x+bbox.w/2)*a.w;
239     int top   = (bbox.y-bbox.h/2)*a.h;
240     int bot   = (bbox.y+bbox.h/2)*a.h;
241 
242     int i;
243     for(i = 0; i < w; ++i){
244         draw_box(a, left+i, top+i, right-i, bot-i, r, g, b);
245     }
246 }
247 
load_alphabet()248 image **load_alphabet()
249 {
250     int i, j;
251     const int nsize = 8;
252     image** alphabets = (image**)xcalloc(nsize, sizeof(image*));
253     for(j = 0; j < nsize; ++j){
254         alphabets[j] = (image*)xcalloc(128, sizeof(image));
255         for(i = 32; i < 127; ++i){
256             char buff[256];
257             sprintf(buff, "data/labels/%d_%d.png", i, j);
258             alphabets[j][i] = load_image_color(buff, 0, 0);
259         }
260     }
261     return alphabets;
262 }
263 
264 
265 
266 // Creates array of detections with prob > thresh and fills best_class for them
get_actual_detections(detection * dets,int dets_num,float thresh,int * selected_detections_num,char ** names)267 detection_with_class* get_actual_detections(detection *dets, int dets_num, float thresh, int* selected_detections_num, char **names)
268 {
269     int selected_num = 0;
270     detection_with_class* result_arr = (detection_with_class*)xcalloc(dets_num, sizeof(detection_with_class));
271     int i;
272     for (i = 0; i < dets_num; ++i) {
273         int best_class = -1;
274         float best_class_prob = thresh;
275         int j;
276         for (j = 0; j < dets[i].classes; ++j) {
277             int show = strncmp(names[j], "dont_show", 9);
278             if (dets[i].prob[j] > best_class_prob && show) {
279                 best_class = j;
280                 best_class_prob = dets[i].prob[j];
281             }
282         }
283         if (best_class >= 0) {
284             result_arr[selected_num].det = dets[i];
285             result_arr[selected_num].best_class = best_class;
286             ++selected_num;
287         }
288     }
289     if (selected_detections_num)
290         *selected_detections_num = selected_num;
291     return result_arr;
292 }
293 
294 // compare to sort detection** by bbox.x
compare_by_lefts(const void * a_ptr,const void * b_ptr)295 int compare_by_lefts(const void *a_ptr, const void *b_ptr) {
296     const detection_with_class* a = (detection_with_class*)a_ptr;
297     const detection_with_class* b = (detection_with_class*)b_ptr;
298     const float delta = (a->det.bbox.x - a->det.bbox.w/2) - (b->det.bbox.x - b->det.bbox.w/2);
299     return delta < 0 ? -1 : delta > 0 ? 1 : 0;
300 }
301 
302 // compare to sort detection** by best_class probability
compare_by_probs(const void * a_ptr,const void * b_ptr)303 int compare_by_probs(const void *a_ptr, const void *b_ptr) {
304     const detection_with_class* a = (detection_with_class*)a_ptr;
305     const detection_with_class* b = (detection_with_class*)b_ptr;
306     float delta = a->det.prob[a->best_class] - b->det.prob[b->best_class];
307     return delta < 0 ? -1 : delta > 0 ? 1 : 0;
308 }
309 
draw_detections_v3(image im,detection * dets,int num,float thresh,char ** names,image ** alphabet,int classes,int ext_output)310 void draw_detections_v3(image im, detection *dets, int num, float thresh, char **names, image **alphabet, int classes, int ext_output)
311 {
312     static int frame_id = 0;
313     frame_id++;
314 
315     int selected_detections_num;
316     detection_with_class* selected_detections = get_actual_detections(dets, num, thresh, &selected_detections_num, names);
317 
318     // text output
319     qsort(selected_detections, selected_detections_num, sizeof(*selected_detections), compare_by_lefts);
320     int i;
321     for (i = 0; i < selected_detections_num; ++i) {
322         const int best_class = selected_detections[i].best_class;
323         printf("%s: %.0f%%", names[best_class],    selected_detections[i].det.prob[best_class] * 100);
324         if (ext_output)
325             printf("\t(left_x: %4.0f   top_y: %4.0f   width: %4.0f   height: %4.0f)\n",
326                 round((selected_detections[i].det.bbox.x - selected_detections[i].det.bbox.w / 2)*im.w),
327                 round((selected_detections[i].det.bbox.y - selected_detections[i].det.bbox.h / 2)*im.h),
328                 round(selected_detections[i].det.bbox.w*im.w), round(selected_detections[i].det.bbox.h*im.h));
329         else
330             printf("\n");
331         int j;
332         for (j = 0; j < classes; ++j) {
333             if (selected_detections[i].det.prob[j] > thresh && j != best_class) {
334                 printf("%s: %.0f%%", names[j], selected_detections[i].det.prob[j] * 100);
335 
336                 if (ext_output)
337                     printf("\t(left_x: %4.0f   top_y: %4.0f   width: %4.0f   height: %4.0f)\n",
338                         round((selected_detections[i].det.bbox.x - selected_detections[i].det.bbox.w / 2)*im.w),
339                         round((selected_detections[i].det.bbox.y - selected_detections[i].det.bbox.h / 2)*im.h),
340                         round(selected_detections[i].det.bbox.w*im.w), round(selected_detections[i].det.bbox.h*im.h));
341                 else
342                     printf("\n");
343             }
344         }
345     }
346 
347     // image output
348     qsort(selected_detections, selected_detections_num, sizeof(*selected_detections), compare_by_probs);
349     for (i = 0; i < selected_detections_num; ++i) {
350             int width = im.h * .002;
351             if (width < 1)
352                 width = 1;
353 
354             /*
355             if(0){
356             width = pow(prob, 1./2.)*10+1;
357             alphabet = 0;
358             }
359             */
360 
361             //printf("%d %s: %.0f%%\n", i, names[selected_detections[i].best_class], prob*100);
362             int offset = selected_detections[i].best_class * 123457 % classes;
363             float red = get_color(2, offset, classes);
364             float green = get_color(1, offset, classes);
365             float blue = get_color(0, offset, classes);
366             float rgb[3];
367 
368             //width = prob*20+2;
369 
370             rgb[0] = red;
371             rgb[1] = green;
372             rgb[2] = blue;
373             box b = selected_detections[i].det.bbox;
374             //printf("%f %f %f %f\n", b.x, b.y, b.w, b.h);
375 
376             int left = (b.x - b.w / 2.)*im.w;
377             int right = (b.x + b.w / 2.)*im.w;
378             int top = (b.y - b.h / 2.)*im.h;
379             int bot = (b.y + b.h / 2.)*im.h;
380 
381             if (left < 0) left = 0;
382             if (right > im.w - 1) right = im.w - 1;
383             if (top < 0) top = 0;
384             if (bot > im.h - 1) bot = im.h - 1;
385 
386             //int b_x_center = (left + right) / 2;
387             //int b_y_center = (top + bot) / 2;
388             //int b_width = right - left;
389             //int b_height = bot - top;
390             //sprintf(labelstr, "%d x %d - w: %d, h: %d", b_x_center, b_y_center, b_width, b_height);
391 
392             // you should create directory: result_img
393             //static int copied_frame_id = -1;
394             //static image copy_img;
395             //if (copied_frame_id != frame_id) {
396             //    copied_frame_id = frame_id;
397             //    if (copy_img.data) free_image(copy_img);
398             //    copy_img = copy_image(im);
399             //}
400             //image cropped_im = crop_image(copy_img, left, top, right - left, bot - top);
401             //static int img_id = 0;
402             //img_id++;
403             //char image_name[1024];
404             //int best_class_id = selected_detections[i].best_class;
405             //sprintf(image_name, "result_img/img_%d_%d_%d_%s.jpg", frame_id, img_id, best_class_id, names[best_class_id]);
406             //save_image(cropped_im, image_name);
407             //free_image(cropped_im);
408 
409             if (im.c == 1) {
410                 draw_box_width_bw(im, left, top, right, bot, width, 0.8);    // 1 channel Black-White
411             }
412             else {
413                 draw_box_width(im, left, top, right, bot, width, red, green, blue); // 3 channels RGB
414             }
415             if (alphabet) {
416                 char labelstr[4096] = { 0 };
417                 strcat(labelstr, names[selected_detections[i].best_class]);
418                 int j;
419                 for (j = 0; j < classes; ++j) {
420                     if (selected_detections[i].det.prob[j] > thresh && j != selected_detections[i].best_class) {
421                         strcat(labelstr, ", ");
422                         strcat(labelstr, names[j]);
423                     }
424                 }
425                 image label = get_label_v3(alphabet, labelstr, (im.h*.02));
426                 draw_label(im, top + width, left, label, rgb);
427                 free_image(label);
428             }
429             if (selected_detections[i].det.mask) {
430                 image mask = float_to_image(14, 14, 1, selected_detections[i].det.mask);
431                 image resized_mask = resize_image(mask, b.w*im.w, b.h*im.h);
432                 image tmask = threshold_image(resized_mask, .5);
433                 embed_image(tmask, im, left, top);
434                 free_image(mask);
435                 free_image(resized_mask);
436                 free_image(tmask);
437             }
438     }
439     free(selected_detections);
440 }
441 
draw_detections(image im,int num,float thresh,box * boxes,float ** probs,char ** names,image ** alphabet,int classes)442 void draw_detections(image im, int num, float thresh, box *boxes, float **probs, char **names, image **alphabet, int classes)
443 {
444     int i;
445 
446     for(i = 0; i < num; ++i){
447         int class_id = max_index(probs[i], classes);
448         float prob = probs[i][class_id];
449         if(prob > thresh){
450 
451             //// for comparison with OpenCV version of DNN Darknet Yolo v2
452             //printf("\n %f, %f, %f, %f, ", boxes[i].x, boxes[i].y, boxes[i].w, boxes[i].h);
453             // int k;
454             //for (k = 0; k < classes; ++k) {
455             //    printf("%f, ", probs[i][k]);
456             //}
457             //printf("\n");
458 
459             int width = im.h * .012;
460 
461             if(0){
462                 width = pow(prob, 1./2.)*10+1;
463                 alphabet = 0;
464             }
465 
466             int offset = class_id*123457 % classes;
467             float red = get_color(2,offset,classes);
468             float green = get_color(1,offset,classes);
469             float blue = get_color(0,offset,classes);
470             float rgb[3];
471 
472             //width = prob*20+2;
473 
474             rgb[0] = red;
475             rgb[1] = green;
476             rgb[2] = blue;
477             box b = boxes[i];
478 
479             int left  = (b.x-b.w/2.)*im.w;
480             int right = (b.x+b.w/2.)*im.w;
481             int top   = (b.y-b.h/2.)*im.h;
482             int bot   = (b.y+b.h/2.)*im.h;
483 
484             if(left < 0) left = 0;
485             if(right > im.w-1) right = im.w-1;
486             if(top < 0) top = 0;
487             if(bot > im.h-1) bot = im.h-1;
488             printf("%s: %.0f%%", names[class_id], prob * 100);
489 
490             //printf(" - id: %d, x_center: %d, y_center: %d, width: %d, height: %d",
491             //    class_id, (right + left) / 2, (bot - top) / 2, right - left, bot - top);
492 
493             printf("\n");
494             draw_box_width(im, left, top, right, bot, width, red, green, blue);
495             if (alphabet) {
496                 image label = get_label(alphabet, names[class_id], (im.h*.03)/10);
497                 draw_label(im, top + width, left, label, rgb);
498             }
499         }
500     }
501 }
502 
transpose_image(image im)503 void transpose_image(image im)
504 {
505     assert(im.w == im.h);
506     int n, m;
507     int c;
508     for(c = 0; c < im.c; ++c){
509         for(n = 0; n < im.w-1; ++n){
510             for(m = n + 1; m < im.w; ++m){
511                 float swap = im.data[m + im.w*(n + im.h*c)];
512                 im.data[m + im.w*(n + im.h*c)] = im.data[n + im.w*(m + im.h*c)];
513                 im.data[n + im.w*(m + im.h*c)] = swap;
514             }
515         }
516     }
517 }
518 
rotate_image_cw(image im,int times)519 void rotate_image_cw(image im, int times)
520 {
521     assert(im.w == im.h);
522     times = (times + 400) % 4;
523     int i, x, y, c;
524     int n = im.w;
525     for(i = 0; i < times; ++i){
526         for(c = 0; c < im.c; ++c){
527             for(x = 0; x < n/2; ++x){
528                 for(y = 0; y < (n-1)/2 + 1; ++y){
529                     float temp = im.data[y + im.w*(x + im.h*c)];
530                     im.data[y + im.w*(x + im.h*c)] = im.data[n-1-x + im.w*(y + im.h*c)];
531                     im.data[n-1-x + im.w*(y + im.h*c)] = im.data[n-1-y + im.w*(n-1-x + im.h*c)];
532                     im.data[n-1-y + im.w*(n-1-x + im.h*c)] = im.data[x + im.w*(n-1-y + im.h*c)];
533                     im.data[x + im.w*(n-1-y + im.h*c)] = temp;
534                 }
535             }
536         }
537     }
538 }
539 
flip_image(image a)540 void flip_image(image a)
541 {
542     int i,j,k;
543     for(k = 0; k < a.c; ++k){
544         for(i = 0; i < a.h; ++i){
545             for(j = 0; j < a.w/2; ++j){
546                 int index = j + a.w*(i + a.h*(k));
547                 int flip = (a.w - j - 1) + a.w*(i + a.h*(k));
548                 float swap = a.data[flip];
549                 a.data[flip] = a.data[index];
550                 a.data[index] = swap;
551             }
552         }
553     }
554 }
555 
image_distance(image a,image b)556 image image_distance(image a, image b)
557 {
558     int i,j;
559     image dist = make_image(a.w, a.h, 1);
560     for(i = 0; i < a.c; ++i){
561         for(j = 0; j < a.h*a.w; ++j){
562             dist.data[j] += pow(a.data[i*a.h*a.w+j]-b.data[i*a.h*a.w+j],2);
563         }
564     }
565     for(j = 0; j < a.h*a.w; ++j){
566         dist.data[j] = sqrt(dist.data[j]);
567     }
568     return dist;
569 }
570 
embed_image(image source,image dest,int dx,int dy)571 void embed_image(image source, image dest, int dx, int dy)
572 {
573     int x,y,k;
574     for(k = 0; k < source.c; ++k){
575         for(y = 0; y < source.h; ++y){
576             for(x = 0; x < source.w; ++x){
577                 float val = get_pixel(source, x,y,k);
578                 set_pixel(dest, dx+x, dy+y, k, val);
579             }
580         }
581     }
582 }
583 
collapse_image_layers(image source,int border)584 image collapse_image_layers(image source, int border)
585 {
586     int h = source.h;
587     h = (h+border)*source.c - border;
588     image dest = make_image(source.w, h, 1);
589     int i;
590     for(i = 0; i < source.c; ++i){
591         image layer = get_image_layer(source, i);
592         int h_offset = i*(source.h+border);
593         embed_image(layer, dest, 0, h_offset);
594         free_image(layer);
595     }
596     return dest;
597 }
598 
constrain_image(image im)599 void constrain_image(image im)
600 {
601     int i;
602     for(i = 0; i < im.w*im.h*im.c; ++i){
603         if(im.data[i] < 0) im.data[i] = 0;
604         if(im.data[i] > 1) im.data[i] = 1;
605     }
606 }
607 
normalize_image(image p)608 void normalize_image(image p)
609 {
610     int i;
611     float min = 9999999;
612     float max = -999999;
613 
614     for(i = 0; i < p.h*p.w*p.c; ++i){
615         float v = p.data[i];
616         if(v < min) min = v;
617         if(v > max) max = v;
618     }
619     if(max - min < .000000001){
620         min = 0;
621         max = 1;
622     }
623     for(i = 0; i < p.c*p.w*p.h; ++i){
624         p.data[i] = (p.data[i] - min)/(max-min);
625     }
626 }
627 
normalize_image2(image p)628 void normalize_image2(image p)
629 {
630     float* min = (float*)xcalloc(p.c, sizeof(float));
631     float* max = (float*)xcalloc(p.c, sizeof(float));
632     int i,j;
633     for(i = 0; i < p.c; ++i) min[i] = max[i] = p.data[i*p.h*p.w];
634 
635     for(j = 0; j < p.c; ++j){
636         for(i = 0; i < p.h*p.w; ++i){
637             float v = p.data[i+j*p.h*p.w];
638             if(v < min[j]) min[j] = v;
639             if(v > max[j]) max[j] = v;
640         }
641     }
642     for(i = 0; i < p.c; ++i){
643         if(max[i] - min[i] < .000000001){
644             min[i] = 0;
645             max[i] = 1;
646         }
647     }
648     for(j = 0; j < p.c; ++j){
649         for(i = 0; i < p.w*p.h; ++i){
650             p.data[i+j*p.h*p.w] = (p.data[i+j*p.h*p.w] - min[j])/(max[j]-min[j]);
651         }
652     }
653     free(min);
654     free(max);
655 }
656 
copy_image_inplace(image src,image dst)657 void copy_image_inplace(image src, image dst)
658 {
659     memcpy(dst.data, src.data, src.h*src.w*src.c * sizeof(float));
660 }
661 
copy_image(image p)662 image copy_image(image p)
663 {
664     image copy = p;
665     copy.data = (float*)xcalloc(p.h * p.w * p.c, sizeof(float));
666     memcpy(copy.data, p.data, p.h*p.w*p.c*sizeof(float));
667     return copy;
668 }
669 
rgbgr_image(image im)670 void rgbgr_image(image im)
671 {
672     int i;
673     for(i = 0; i < im.w*im.h; ++i){
674         float swap = im.data[i];
675         im.data[i] = im.data[i+im.w*im.h*2];
676         im.data[i+im.w*im.h*2] = swap;
677     }
678 }
679 
show_image(image p,const char * name)680 void show_image(image p, const char *name)
681 {
682 #ifdef OPENCV
683     show_image_cv(p, name);
684 #else
685     fprintf(stderr, "Not compiled with OpenCV, saving to %s.png instead\n", name);
686     save_image(p, name);
687 #endif  // OPENCV
688 }
689 
save_image_png(image im,const char * name)690 void save_image_png(image im, const char *name)
691 {
692     char buff[256];
693     //sprintf(buff, "%s (%d)", name, windows);
694     sprintf(buff, "%s.png", name);
695     unsigned char* data = (unsigned char*)xcalloc(im.w * im.h * im.c, sizeof(unsigned char));
696     int i,k;
697     for(k = 0; k < im.c; ++k){
698         for(i = 0; i < im.w*im.h; ++i){
699             data[i*im.c+k] = (unsigned char) (255*im.data[i + k*im.w*im.h]);
700         }
701     }
702     int success = stbi_write_png(buff, im.w, im.h, im.c, data, im.w*im.c);
703     free(data);
704     if(!success) fprintf(stderr, "Failed to write image %s\n", buff);
705 }
706 
save_image_options(image im,const char * name,IMTYPE f,int quality)707 void save_image_options(image im, const char *name, IMTYPE f, int quality)
708 {
709     char buff[256];
710     //sprintf(buff, "%s (%d)", name, windows);
711     if (f == PNG)       sprintf(buff, "%s.png", name);
712     else if (f == BMP) sprintf(buff, "%s.bmp", name);
713     else if (f == TGA) sprintf(buff, "%s.tga", name);
714     else if (f == JPG) sprintf(buff, "%s.jpg", name);
715     else               sprintf(buff, "%s.png", name);
716     unsigned char* data = (unsigned char*)xcalloc(im.w * im.h * im.c, sizeof(unsigned char));
717     int i, k;
718     for (k = 0; k < im.c; ++k) {
719         for (i = 0; i < im.w*im.h; ++i) {
720             data[i*im.c + k] = (unsigned char)(255 * im.data[i + k*im.w*im.h]);
721         }
722     }
723     int success = 0;
724     if (f == PNG)       success = stbi_write_png(buff, im.w, im.h, im.c, data, im.w*im.c);
725     else if (f == BMP) success = stbi_write_bmp(buff, im.w, im.h, im.c, data);
726     else if (f == TGA) success = stbi_write_tga(buff, im.w, im.h, im.c, data);
727     else if (f == JPG) success = stbi_write_jpg(buff, im.w, im.h, im.c, data, quality);
728     free(data);
729     if (!success) fprintf(stderr, "Failed to write image %s\n", buff);
730 }
731 
save_image(image im,const char * name)732 void save_image(image im, const char *name)
733 {
734     save_image_options(im, name, JPG, 80);
735 }
736 
save_image_jpg(image p,const char * name)737 void save_image_jpg(image p, const char *name)
738 {
739     save_image_options(p, name, JPG, 80);
740 }
741 
show_image_layers(image p,char * name)742 void show_image_layers(image p, char *name)
743 {
744     int i;
745     char buff[256];
746     for(i = 0; i < p.c; ++i){
747         sprintf(buff, "%s - Layer %d", name, i);
748         image layer = get_image_layer(p, i);
749         show_image(layer, buff);
750         free_image(layer);
751     }
752 }
753 
show_image_collapsed(image p,char * name)754 void show_image_collapsed(image p, char *name)
755 {
756     image c = collapse_image_layers(p, 1);
757     show_image(c, name);
758     free_image(c);
759 }
760 
make_empty_image(int w,int h,int c)761 image make_empty_image(int w, int h, int c)
762 {
763     image out;
764     out.data = 0;
765     out.h = h;
766     out.w = w;
767     out.c = c;
768     return out;
769 }
770 
make_image(int w,int h,int c)771 image make_image(int w, int h, int c)
772 {
773     image out = make_empty_image(w,h,c);
774     out.data = (float*)xcalloc(h * w * c, sizeof(float));
775     return out;
776 }
777 
make_random_image(int w,int h,int c)778 image make_random_image(int w, int h, int c)
779 {
780     image out = make_empty_image(w,h,c);
781     out.data = (float*)xcalloc(h * w * c, sizeof(float));
782     int i;
783     for(i = 0; i < w*h*c; ++i){
784         out.data[i] = (rand_normal() * .25) + .5;
785     }
786     return out;
787 }
788 
float_to_image_scaled(int w,int h,int c,float * data)789 image float_to_image_scaled(int w, int h, int c, float *data)
790 {
791     image out = make_image(w, h, c);
792     int abs_max = 0;
793     int i = 0;
794     for (i = 0; i < w*h*c; ++i) {
795         if (fabs(data[i]) > abs_max) abs_max = fabs(data[i]);
796     }
797     for (i = 0; i < w*h*c; ++i) {
798         out.data[i] = data[i] / abs_max;
799     }
800     return out;
801 }
802 
float_to_image(int w,int h,int c,float * data)803 image float_to_image(int w, int h, int c, float *data)
804 {
805     image out = make_empty_image(w,h,c);
806     out.data = data;
807     return out;
808 }
809 
810 
rotate_crop_image(image im,float rad,float s,int w,int h,float dx,float dy,float aspect)811 image rotate_crop_image(image im, float rad, float s, int w, int h, float dx, float dy, float aspect)
812 {
813     int x, y, c;
814     float cx = im.w/2.;
815     float cy = im.h/2.;
816     image rot = make_image(w, h, im.c);
817     for(c = 0; c < im.c; ++c){
818         for(y = 0; y < h; ++y){
819             for(x = 0; x < w; ++x){
820                 float rx = cos(rad)*((x - w/2.)/s*aspect + dx/s*aspect) - sin(rad)*((y - h/2.)/s + dy/s) + cx;
821                 float ry = sin(rad)*((x - w/2.)/s*aspect + dx/s*aspect) + cos(rad)*((y - h/2.)/s + dy/s) + cy;
822                 float val = bilinear_interpolate(im, rx, ry, c);
823                 set_pixel(rot, x, y, c, val);
824             }
825         }
826     }
827     return rot;
828 }
829 
rotate_image(image im,float rad)830 image rotate_image(image im, float rad)
831 {
832     int x, y, c;
833     float cx = im.w/2.;
834     float cy = im.h/2.;
835     image rot = make_image(im.w, im.h, im.c);
836     for(c = 0; c < im.c; ++c){
837         for(y = 0; y < im.h; ++y){
838             for(x = 0; x < im.w; ++x){
839                 float rx = cos(rad)*(x-cx) - sin(rad)*(y-cy) + cx;
840                 float ry = sin(rad)*(x-cx) + cos(rad)*(y-cy) + cy;
841                 float val = bilinear_interpolate(im, rx, ry, c);
842                 set_pixel(rot, x, y, c, val);
843             }
844         }
845     }
846     return rot;
847 }
848 
translate_image(image m,float s)849 void translate_image(image m, float s)
850 {
851     int i;
852     for(i = 0; i < m.h*m.w*m.c; ++i) m.data[i] += s;
853 }
854 
scale_image(image m,float s)855 void scale_image(image m, float s)
856 {
857     int i;
858     for(i = 0; i < m.h*m.w*m.c; ++i) m.data[i] *= s;
859 }
860 
crop_image(image im,int dx,int dy,int w,int h)861 image crop_image(image im, int dx, int dy, int w, int h)
862 {
863     image cropped = make_image(w, h, im.c);
864     int i, j, k;
865     for(k = 0; k < im.c; ++k){
866         for(j = 0; j < h; ++j){
867             for(i = 0; i < w; ++i){
868                 int r = j + dy;
869                 int c = i + dx;
870                 float val = 0;
871                 r = constrain_int(r, 0, im.h-1);
872                 c = constrain_int(c, 0, im.w-1);
873                 if (r >= 0 && r < im.h && c >= 0 && c < im.w) {
874                     val = get_pixel(im, c, r, k);
875                 }
876                 set_pixel(cropped, i, j, k, val);
877             }
878         }
879     }
880     return cropped;
881 }
882 
best_3d_shift_r(image a,image b,int min,int max)883 int best_3d_shift_r(image a, image b, int min, int max)
884 {
885     if(min == max) return min;
886     int mid = floor((min + max) / 2.);
887     image c1 = crop_image(b, 0, mid, b.w, b.h);
888     image c2 = crop_image(b, 0, mid+1, b.w, b.h);
889     float d1 = dist_array(c1.data, a.data, a.w*a.h*a.c, 10);
890     float d2 = dist_array(c2.data, a.data, a.w*a.h*a.c, 10);
891     free_image(c1);
892     free_image(c2);
893     if(d1 < d2) return best_3d_shift_r(a, b, min, mid);
894     else return best_3d_shift_r(a, b, mid+1, max);
895 }
896 
best_3d_shift(image a,image b,int min,int max)897 int best_3d_shift(image a, image b, int min, int max)
898 {
899     int i;
900     int best = 0;
901     float best_distance = FLT_MAX;
902     for(i = min; i <= max; i += 2){
903         image c = crop_image(b, 0, i, b.w, b.h);
904         float d = dist_array(c.data, a.data, a.w*a.h*a.c, 100);
905         if(d < best_distance){
906             best_distance = d;
907             best = i;
908         }
909         printf("%d %f\n", i, d);
910         free_image(c);
911     }
912     return best;
913 }
914 
composite_3d(char * f1,char * f2,char * out,int delta)915 void composite_3d(char *f1, char *f2, char *out, int delta)
916 {
917     if(!out) out = "out";
918     image a = load_image(f1, 0,0,0);
919     image b = load_image(f2, 0,0,0);
920     int shift = best_3d_shift_r(a, b, -a.h/100, a.h/100);
921 
922     image c1 = crop_image(b, 10, shift, b.w, b.h);
923     float d1 = dist_array(c1.data, a.data, a.w*a.h*a.c, 100);
924     image c2 = crop_image(b, -10, shift, b.w, b.h);
925     float d2 = dist_array(c2.data, a.data, a.w*a.h*a.c, 100);
926 
927     if(d2 < d1 && 0){
928         image swap = a;
929         a = b;
930         b = swap;
931         shift = -shift;
932         printf("swapped, %d\n", shift);
933     }
934     else{
935         printf("%d\n", shift);
936     }
937 
938     image c = crop_image(b, delta, shift, a.w, a.h);
939     int i;
940     for(i = 0; i < c.w*c.h; ++i){
941         c.data[i] = a.data[i];
942     }
943 #ifdef OPENCV
944     save_image_jpg(c, out);
945 #else
946     save_image(c, out);
947 #endif
948 }
949 
fill_image(image m,float s)950 void fill_image(image m, float s)
951 {
952     int i;
953     for (i = 0; i < m.h*m.w*m.c; ++i) m.data[i] = s;
954 }
955 
letterbox_image_into(image im,int w,int h,image boxed)956 void letterbox_image_into(image im, int w, int h, image boxed)
957 {
958     int new_w = im.w;
959     int new_h = im.h;
960     if (((float)w / im.w) < ((float)h / im.h)) {
961         new_w = w;
962         new_h = (im.h * w) / im.w;
963     }
964     else {
965         new_h = h;
966         new_w = (im.w * h) / im.h;
967     }
968     image resized = resize_image(im, new_w, new_h);
969     embed_image(resized, boxed, (w - new_w) / 2, (h - new_h) / 2);
970     free_image(resized);
971 }
972 
letterbox_image(image im,int w,int h)973 image letterbox_image(image im, int w, int h)
974 {
975     int new_w = im.w;
976     int new_h = im.h;
977     if (((float)w / im.w) < ((float)h / im.h)) {
978         new_w = w;
979         new_h = (im.h * w) / im.w;
980     }
981     else {
982         new_h = h;
983         new_w = (im.w * h) / im.h;
984     }
985     image resized = resize_image(im, new_w, new_h);
986     image boxed = make_image(w, h, im.c);
987     fill_image(boxed, .5);
988     //int i;
989     //for(i = 0; i < boxed.w*boxed.h*boxed.c; ++i) boxed.data[i] = 0;
990     embed_image(resized, boxed, (w - new_w) / 2, (h - new_h) / 2);
991     free_image(resized);
992     return boxed;
993 }
994 
resize_max(image im,int max)995 image resize_max(image im, int max)
996 {
997     int w = im.w;
998     int h = im.h;
999     if(w > h){
1000         h = (h * max) / w;
1001         w = max;
1002     } else {
1003         w = (w * max) / h;
1004         h = max;
1005     }
1006     if(w == im.w && h == im.h) return im;
1007     image resized = resize_image(im, w, h);
1008     return resized;
1009 }
1010 
resize_min(image im,int min)1011 image resize_min(image im, int min)
1012 {
1013     int w = im.w;
1014     int h = im.h;
1015     if(w < h){
1016         h = (h * min) / w;
1017         w = min;
1018     } else {
1019         w = (w * min) / h;
1020         h = min;
1021     }
1022     if(w == im.w && h == im.h) return im;
1023     image resized = resize_image(im, w, h);
1024     return resized;
1025 }
1026 
random_crop_image(image im,int w,int h)1027 image random_crop_image(image im, int w, int h)
1028 {
1029     int dx = rand_int(0, im.w - w);
1030     int dy = rand_int(0, im.h - h);
1031     image crop = crop_image(im, dx, dy, w, h);
1032     return crop;
1033 }
1034 
random_augment_image(image im,float angle,float aspect,int low,int high,int size)1035 image random_augment_image(image im, float angle, float aspect, int low, int high, int size)
1036 {
1037     aspect = rand_scale(aspect);
1038     int r = rand_int(low, high);
1039     int min = (im.h < im.w*aspect) ? im.h : im.w*aspect;
1040     float scale = (float)r / min;
1041 
1042     float rad = rand_uniform(-angle, angle) * 2.0 * M_PI / 360.;
1043 
1044     float dx = (im.w*scale/aspect - size) / 2.;
1045     float dy = (im.h*scale - size) / 2.;
1046     if(dx < 0) dx = 0;
1047     if(dy < 0) dy = 0;
1048     dx = rand_uniform(-dx, dx);
1049     dy = rand_uniform(-dy, dy);
1050 
1051     image crop = rotate_crop_image(im, rad, scale, size, size, dx, dy, aspect);
1052 
1053     return crop;
1054 }
1055 
three_way_max(float a,float b,float c)1056 float three_way_max(float a, float b, float c)
1057 {
1058     return (a > b) ? ( (a > c) ? a : c) : ( (b > c) ? b : c) ;
1059 }
1060 
three_way_min(float a,float b,float c)1061 float three_way_min(float a, float b, float c)
1062 {
1063     return (a < b) ? ( (a < c) ? a : c) : ( (b < c) ? b : c) ;
1064 }
1065 
1066 // http://www.cs.rit.edu/~ncs/color/t_convert.html
rgb_to_hsv(image im)1067 void rgb_to_hsv(image im)
1068 {
1069     assert(im.c == 3);
1070     int i, j;
1071     float r, g, b;
1072     float h, s, v;
1073     for(j = 0; j < im.h; ++j){
1074         for(i = 0; i < im.w; ++i){
1075             r = get_pixel(im, i , j, 0);
1076             g = get_pixel(im, i , j, 1);
1077             b = get_pixel(im, i , j, 2);
1078             float max = three_way_max(r,g,b);
1079             float min = three_way_min(r,g,b);
1080             float delta = max - min;
1081             v = max;
1082             if(max == 0){
1083                 s = 0;
1084                 h = 0;
1085             }else{
1086                 s = delta/max;
1087                 if(r == max){
1088                     h = (g - b) / delta;
1089                 } else if (g == max) {
1090                     h = 2 + (b - r) / delta;
1091                 } else {
1092                     h = 4 + (r - g) / delta;
1093                 }
1094                 if (h < 0) h += 6;
1095                 h = h/6.;
1096             }
1097             set_pixel(im, i, j, 0, h);
1098             set_pixel(im, i, j, 1, s);
1099             set_pixel(im, i, j, 2, v);
1100         }
1101     }
1102 }
1103 
hsv_to_rgb(image im)1104 void hsv_to_rgb(image im)
1105 {
1106     assert(im.c == 3);
1107     int i, j;
1108     float r, g, b;
1109     float h, s, v;
1110     float f, p, q, t;
1111     for(j = 0; j < im.h; ++j){
1112         for(i = 0; i < im.w; ++i){
1113             h = 6 * get_pixel(im, i , j, 0);
1114             s = get_pixel(im, i , j, 1);
1115             v = get_pixel(im, i , j, 2);
1116             if (s == 0) {
1117                 r = g = b = v;
1118             } else {
1119                 int index = floor(h);
1120                 f = h - index;
1121                 p = v*(1-s);
1122                 q = v*(1-s*f);
1123                 t = v*(1-s*(1-f));
1124                 if(index == 0){
1125                     r = v; g = t; b = p;
1126                 } else if(index == 1){
1127                     r = q; g = v; b = p;
1128                 } else if(index == 2){
1129                     r = p; g = v; b = t;
1130                 } else if(index == 3){
1131                     r = p; g = q; b = v;
1132                 } else if(index == 4){
1133                     r = t; g = p; b = v;
1134                 } else {
1135                     r = v; g = p; b = q;
1136                 }
1137             }
1138             set_pixel(im, i, j, 0, r);
1139             set_pixel(im, i, j, 1, g);
1140             set_pixel(im, i, j, 2, b);
1141         }
1142     }
1143 }
1144 
grayscale_image(image im)1145 image grayscale_image(image im)
1146 {
1147     assert(im.c == 3);
1148     int i, j, k;
1149     image gray = make_image(im.w, im.h, 1);
1150     float scale[] = {0.587, 0.299, 0.114};
1151     for(k = 0; k < im.c; ++k){
1152         for(j = 0; j < im.h; ++j){
1153             for(i = 0; i < im.w; ++i){
1154                 gray.data[i+im.w*j] += scale[k]*get_pixel(im, i, j, k);
1155             }
1156         }
1157     }
1158     return gray;
1159 }
1160 
threshold_image(image im,float thresh)1161 image threshold_image(image im, float thresh)
1162 {
1163     int i;
1164     image t = make_image(im.w, im.h, im.c);
1165     for(i = 0; i < im.w*im.h*im.c; ++i){
1166         t.data[i] = im.data[i]>thresh ? 1 : 0;
1167     }
1168     return t;
1169 }
1170 
blend_image(image fore,image back,float alpha)1171 image blend_image(image fore, image back, float alpha)
1172 {
1173     assert(fore.w == back.w && fore.h == back.h && fore.c == back.c);
1174     image blend = make_image(fore.w, fore.h, fore.c);
1175     int i, j, k;
1176     for(k = 0; k < fore.c; ++k){
1177         for(j = 0; j < fore.h; ++j){
1178             for(i = 0; i < fore.w; ++i){
1179                 float val = alpha * get_pixel(fore, i, j, k) +
1180                     (1 - alpha)* get_pixel(back, i, j, k);
1181                 set_pixel(blend, i, j, k, val);
1182             }
1183         }
1184     }
1185     return blend;
1186 }
1187 
scale_image_channel(image im,int c,float v)1188 void scale_image_channel(image im, int c, float v)
1189 {
1190     int i, j;
1191     for(j = 0; j < im.h; ++j){
1192         for(i = 0; i < im.w; ++i){
1193             float pix = get_pixel(im, i, j, c);
1194             pix = pix*v;
1195             set_pixel(im, i, j, c, pix);
1196         }
1197     }
1198 }
1199 
translate_image_channel(image im,int c,float v)1200 void translate_image_channel(image im, int c, float v)
1201 {
1202     int i, j;
1203     for(j = 0; j < im.h; ++j){
1204         for(i = 0; i < im.w; ++i){
1205             float pix = get_pixel(im, i, j, c);
1206             pix = pix+v;
1207             set_pixel(im, i, j, c, pix);
1208         }
1209     }
1210 }
1211 
binarize_image(image im)1212 image binarize_image(image im)
1213 {
1214     image c = copy_image(im);
1215     int i;
1216     for(i = 0; i < im.w * im.h * im.c; ++i){
1217         if(c.data[i] > .5) c.data[i] = 1;
1218         else c.data[i] = 0;
1219     }
1220     return c;
1221 }
1222 
saturate_image(image im,float sat)1223 void saturate_image(image im, float sat)
1224 {
1225     rgb_to_hsv(im);
1226     scale_image_channel(im, 1, sat);
1227     hsv_to_rgb(im);
1228     constrain_image(im);
1229 }
1230 
hue_image(image im,float hue)1231 void hue_image(image im, float hue)
1232 {
1233     rgb_to_hsv(im);
1234     int i;
1235     for(i = 0; i < im.w*im.h; ++i){
1236         im.data[i] = im.data[i] + hue;
1237         if (im.data[i] > 1) im.data[i] -= 1;
1238         if (im.data[i] < 0) im.data[i] += 1;
1239     }
1240     hsv_to_rgb(im);
1241     constrain_image(im);
1242 }
1243 
exposure_image(image im,float sat)1244 void exposure_image(image im, float sat)
1245 {
1246     rgb_to_hsv(im);
1247     scale_image_channel(im, 2, sat);
1248     hsv_to_rgb(im);
1249     constrain_image(im);
1250 }
1251 
distort_image(image im,float hue,float sat,float val)1252 void distort_image(image im, float hue, float sat, float val)
1253 {
1254     if (im.c >= 3)
1255     {
1256         rgb_to_hsv(im);
1257         scale_image_channel(im, 1, sat);
1258         scale_image_channel(im, 2, val);
1259         int i;
1260         for(i = 0; i < im.w*im.h; ++i){
1261             im.data[i] = im.data[i] + hue;
1262             if (im.data[i] > 1) im.data[i] -= 1;
1263             if (im.data[i] < 0) im.data[i] += 1;
1264         }
1265         hsv_to_rgb(im);
1266     }
1267     else
1268     {
1269         scale_image_channel(im, 0, val);
1270     }
1271     constrain_image(im);
1272 }
1273 
random_distort_image(image im,float hue,float saturation,float exposure)1274 void random_distort_image(image im, float hue, float saturation, float exposure)
1275 {
1276     float dhue = rand_uniform_strong(-hue, hue);
1277     float dsat = rand_scale(saturation);
1278     float dexp = rand_scale(exposure);
1279     distort_image(im, dhue, dsat, dexp);
1280 }
1281 
saturate_exposure_image(image im,float sat,float exposure)1282 void saturate_exposure_image(image im, float sat, float exposure)
1283 {
1284     rgb_to_hsv(im);
1285     scale_image_channel(im, 1, sat);
1286     scale_image_channel(im, 2, exposure);
1287     hsv_to_rgb(im);
1288     constrain_image(im);
1289 }
1290 
bilinear_interpolate(image im,float x,float y,int c)1291 float bilinear_interpolate(image im, float x, float y, int c)
1292 {
1293     int ix = (int) floorf(x);
1294     int iy = (int) floorf(y);
1295 
1296     float dx = x - ix;
1297     float dy = y - iy;
1298 
1299     float val = (1-dy) * (1-dx) * get_pixel_extend(im, ix, iy, c) +
1300         dy     * (1-dx) * get_pixel_extend(im, ix, iy+1, c) +
1301         (1-dy) *   dx   * get_pixel_extend(im, ix+1, iy, c) +
1302         dy     *   dx   * get_pixel_extend(im, ix+1, iy+1, c);
1303     return val;
1304 }
1305 
quantize_image(image im)1306 void quantize_image(image im)
1307 {
1308     int size = im.c * im.w * im.h;
1309     int i;
1310     for (i = 0; i < size; ++i) im.data[i] = (int)(im.data[i] * 255) / 255. + (0.5/255);
1311 }
1312 
make_image_red(image im)1313 void make_image_red(image im)
1314 {
1315     int r, c, k;
1316     for (r = 0; r < im.h; ++r) {
1317         for (c = 0; c < im.w; ++c) {
1318             float val = 0;
1319             for (k = 0; k < im.c; ++k) {
1320                 val += get_pixel(im, c, r, k);
1321                 set_pixel(im, c, r, k, 0);
1322             }
1323             for (k = 0; k < im.c; ++k) {
1324                 //set_pixel(im, c, r, k, val);
1325             }
1326             set_pixel(im, c, r, 0, val);
1327         }
1328     }
1329 }
1330 
make_attention_image(int img_size,float * original_delta_cpu,float * original_input_cpu,int w,int h,int c)1331 image make_attention_image(int img_size, float *original_delta_cpu, float *original_input_cpu, int w, int h, int c)
1332 {
1333     image attention_img;
1334     attention_img.w = w;
1335     attention_img.h = h;
1336     attention_img.c = c;
1337     attention_img.data = original_delta_cpu;
1338     make_image_red(attention_img);
1339 
1340     int k;
1341     float min_val = 999999, mean_val = 0, max_val = -999999;
1342     for (k = 0; k < img_size; ++k) {
1343         if (original_delta_cpu[k] < min_val) min_val = original_delta_cpu[k];
1344         if (original_delta_cpu[k] > max_val) max_val = original_delta_cpu[k];
1345         mean_val += original_delta_cpu[k];
1346     }
1347     mean_val = mean_val / img_size;
1348     float range = max_val - min_val;
1349 
1350     for (k = 0; k < img_size; ++k) {
1351         float val = original_delta_cpu[k];
1352         val = fabs(mean_val - val) / range;
1353         original_delta_cpu[k] = val * 4;
1354     }
1355 
1356     image resized = resize_image(attention_img, w / 4, h / 4);
1357     attention_img = resize_image(resized, w, h);
1358     free_image(resized);
1359     for (k = 0; k < img_size; ++k) attention_img.data[k] += original_input_cpu[k];
1360 
1361     //normalize_image(attention_img);
1362     //show_image(attention_img, "delta");
1363     return attention_img;
1364 }
1365 
resize_image(image im,int w,int h)1366 image resize_image(image im, int w, int h)
1367 {
1368     if (im.w == w && im.h == h) return copy_image(im);
1369 
1370     image resized = make_image(w, h, im.c);
1371     image part = make_image(w, im.h, im.c);
1372     int r, c, k;
1373     float w_scale = (float)(im.w - 1) / (w - 1);
1374     float h_scale = (float)(im.h - 1) / (h - 1);
1375     for(k = 0; k < im.c; ++k){
1376         for(r = 0; r < im.h; ++r){
1377             for(c = 0; c < w; ++c){
1378                 float val = 0;
1379                 if(c == w-1 || im.w == 1){
1380                     val = get_pixel(im, im.w-1, r, k);
1381                 } else {
1382                     float sx = c*w_scale;
1383                     int ix = (int) sx;
1384                     float dx = sx - ix;
1385                     val = (1 - dx) * get_pixel(im, ix, r, k) + dx * get_pixel(im, ix+1, r, k);
1386                 }
1387                 set_pixel(part, c, r, k, val);
1388             }
1389         }
1390     }
1391     for(k = 0; k < im.c; ++k){
1392         for(r = 0; r < h; ++r){
1393             float sy = r*h_scale;
1394             int iy = (int) sy;
1395             float dy = sy - iy;
1396             for(c = 0; c < w; ++c){
1397                 float val = (1-dy) * get_pixel(part, c, iy, k);
1398                 set_pixel(resized, c, r, k, val);
1399             }
1400             if(r == h-1 || im.h == 1) continue;
1401             for(c = 0; c < w; ++c){
1402                 float val = dy * get_pixel(part, c, iy+1, k);
1403                 add_pixel(resized, c, r, k, val);
1404             }
1405         }
1406     }
1407 
1408     free_image(part);
1409     return resized;
1410 }
1411 
1412 
test_resize(char * filename)1413 void test_resize(char *filename)
1414 {
1415     image im = load_image(filename, 0,0, 3);
1416     float mag = mag_array(im.data, im.w*im.h*im.c);
1417     printf("L2 Norm: %f\n", mag);
1418     image gray = grayscale_image(im);
1419 
1420     image c1 = copy_image(im);
1421     image c2 = copy_image(im);
1422     image c3 = copy_image(im);
1423     image c4 = copy_image(im);
1424     distort_image(c1, .1, 1.5, 1.5);
1425     distort_image(c2, -.1, .66666, .66666);
1426     distort_image(c3, .1, 1.5, .66666);
1427     distort_image(c4, .1, .66666, 1.5);
1428 
1429 
1430     show_image(im,   "Original");
1431     show_image(gray, "Gray");
1432     show_image(c1, "C1");
1433     show_image(c2, "C2");
1434     show_image(c3, "C3");
1435     show_image(c4, "C4");
1436 
1437 #ifdef OPENCV
1438     while(1){
1439         image aug = random_augment_image(im, 0, .75, 320, 448, 320);
1440         show_image(aug, "aug");
1441         free_image(aug);
1442 
1443 
1444         float exposure = 1.15;
1445         float saturation = 1.15;
1446         float hue = .05;
1447 
1448         image c = copy_image(im);
1449 
1450         float dexp = rand_scale(exposure);
1451         float dsat = rand_scale(saturation);
1452         float dhue = rand_uniform(-hue, hue);
1453 
1454         distort_image(c, dhue, dsat, dexp);
1455         show_image(c, "rand");
1456         printf("%f %f %f\n", dhue, dsat, dexp);
1457         free_image(c);
1458         wait_until_press_key_cv();
1459     }
1460 #endif
1461 }
1462 
1463 
load_image_stb(char * filename,int channels)1464 image load_image_stb(char *filename, int channels)
1465 {
1466     int w, h, c;
1467     unsigned char *data = stbi_load(filename, &w, &h, &c, channels);
1468     if (!data) {
1469         char shrinked_filename[1024];
1470         if (strlen(filename) >= 1024) sprintf(shrinked_filename, "name is too long");
1471         else sprintf(shrinked_filename, "%s", filename);
1472         fprintf(stderr, "Cannot load image \"%s\"\nSTB Reason: %s\n", shrinked_filename, stbi_failure_reason());
1473         FILE* fw = fopen("bad.list", "a");
1474         fwrite(shrinked_filename, sizeof(char), strlen(shrinked_filename), fw);
1475         char *new_line = "\n";
1476         fwrite(new_line, sizeof(char), strlen(new_line), fw);
1477         fclose(fw);
1478         if (check_mistakes) {
1479             printf("\n Error in load_image_stb() \n");
1480             getchar();
1481         }
1482         return make_image(10, 10, 3);
1483         //exit(EXIT_FAILURE);
1484     }
1485     if(channels) c = channels;
1486     int i,j,k;
1487     image im = make_image(w, h, c);
1488     for(k = 0; k < c; ++k){
1489         for(j = 0; j < h; ++j){
1490             for(i = 0; i < w; ++i){
1491                 int dst_index = i + w*j + w*h*k;
1492                 int src_index = k + c*i + c*w*j;
1493                 im.data[dst_index] = (float)data[src_index]/255.;
1494             }
1495         }
1496     }
1497     free(data);
1498     return im;
1499 }
1500 
load_image_stb_resize(char * filename,int w,int h,int c)1501 image load_image_stb_resize(char *filename, int w, int h, int c)
1502 {
1503     image out = load_image_stb(filename, c);    // without OpenCV
1504 
1505     if ((h && w) && (h != out.h || w != out.w)) {
1506         image resized = resize_image(out, w, h);
1507         free_image(out);
1508         out = resized;
1509     }
1510     return out;
1511 }
1512 
load_image(char * filename,int w,int h,int c)1513 image load_image(char *filename, int w, int h, int c)
1514 {
1515 #ifdef OPENCV
1516     //image out = load_image_stb(filename, c);
1517     image out = load_image_cv(filename, c);
1518 #else
1519     image out = load_image_stb(filename, c);    // without OpenCV
1520 #endif  // OPENCV
1521 
1522     if((h && w) && (h != out.h || w != out.w)){
1523         image resized = resize_image(out, w, h);
1524         free_image(out);
1525         out = resized;
1526     }
1527     return out;
1528 }
1529 
load_image_color(char * filename,int w,int h)1530 image load_image_color(char *filename, int w, int h)
1531 {
1532     return load_image(filename, w, h, 3);
1533 }
1534 
get_image_layer(image m,int l)1535 image get_image_layer(image m, int l)
1536 {
1537     image out = make_image(m.w, m.h, 1);
1538     int i;
1539     for(i = 0; i < m.h*m.w; ++i){
1540         out.data[i] = m.data[i+l*m.h*m.w];
1541     }
1542     return out;
1543 }
1544 
print_image(image m)1545 void print_image(image m)
1546 {
1547     int i, j, k;
1548     for(i =0 ; i < m.c; ++i){
1549         for(j =0 ; j < m.h; ++j){
1550             for(k = 0; k < m.w; ++k){
1551                 printf("%.2lf, ", m.data[i*m.h*m.w + j*m.w + k]);
1552                 if(k > 30) break;
1553             }
1554             printf("\n");
1555             if(j > 30) break;
1556         }
1557         printf("\n");
1558     }
1559     printf("\n");
1560 }
1561 
collapse_images_vert(image * ims,int n)1562 image collapse_images_vert(image *ims, int n)
1563 {
1564     int color = 1;
1565     int border = 1;
1566     int h,w,c;
1567     w = ims[0].w;
1568     h = (ims[0].h + border) * n - border;
1569     c = ims[0].c;
1570     if(c != 3 || !color){
1571         w = (w+border)*c - border;
1572         c = 1;
1573     }
1574 
1575     image filters = make_image(w, h, c);
1576     int i,j;
1577     for(i = 0; i < n; ++i){
1578         int h_offset = i*(ims[0].h+border);
1579         image copy = copy_image(ims[i]);
1580         //normalize_image(copy);
1581         if(c == 3 && color){
1582             embed_image(copy, filters, 0, h_offset);
1583         }
1584         else{
1585             for(j = 0; j < copy.c; ++j){
1586                 int w_offset = j*(ims[0].w+border);
1587                 image layer = get_image_layer(copy, j);
1588                 embed_image(layer, filters, w_offset, h_offset);
1589                 free_image(layer);
1590             }
1591         }
1592         free_image(copy);
1593     }
1594     return filters;
1595 }
1596 
collapse_images_horz(image * ims,int n)1597 image collapse_images_horz(image *ims, int n)
1598 {
1599     int color = 1;
1600     int border = 1;
1601     int h,w,c;
1602     int size = ims[0].h;
1603     h = size;
1604     w = (ims[0].w + border) * n - border;
1605     c = ims[0].c;
1606     if(c != 3 || !color){
1607         h = (h+border)*c - border;
1608         c = 1;
1609     }
1610 
1611     image filters = make_image(w, h, c);
1612     int i,j;
1613     for(i = 0; i < n; ++i){
1614         int w_offset = i*(size+border);
1615         image copy = copy_image(ims[i]);
1616         //normalize_image(copy);
1617         if(c == 3 && color){
1618             embed_image(copy, filters, w_offset, 0);
1619         }
1620         else{
1621             for(j = 0; j < copy.c; ++j){
1622                 int h_offset = j*(size+border);
1623                 image layer = get_image_layer(copy, j);
1624                 embed_image(layer, filters, w_offset, h_offset);
1625                 free_image(layer);
1626             }
1627         }
1628         free_image(copy);
1629     }
1630     return filters;
1631 }
1632 
show_image_normalized(image im,const char * name)1633 void show_image_normalized(image im, const char *name)
1634 {
1635     image c = copy_image(im);
1636     normalize_image(c);
1637     show_image(c, name);
1638     free_image(c);
1639 }
1640 
show_images(image * ims,int n,char * window)1641 void show_images(image *ims, int n, char *window)
1642 {
1643     image m = collapse_images_vert(ims, n);
1644     /*
1645        int w = 448;
1646        int h = ((float)m.h/m.w) * 448;
1647        if(h > 896){
1648        h = 896;
1649        w = ((float)m.w/m.h) * 896;
1650        }
1651        image sized = resize_image(m, w, h);
1652      */
1653     normalize_image(m);
1654     save_image(m, window);
1655     show_image(m, window);
1656     free_image(m);
1657 }
1658 
free_image(image m)1659 void free_image(image m)
1660 {
1661     if(m.data){
1662         free(m.data);
1663     }
1664 }
1665 
1666 // Fast copy data from a contiguous byte array into the image.
copy_image_from_bytes(image im,char * pdata)1667 LIB_API void copy_image_from_bytes(image im, char *pdata)
1668 {
1669     unsigned char *data = (unsigned char*)pdata;
1670     int i, k, j;
1671     int w = im.w;
1672     int h = im.h;
1673     int c = im.c;
1674     for (k = 0; k < c; ++k) {
1675         for (j = 0; j < h; ++j) {
1676             for (i = 0; i < w; ++i) {
1677                 int dst_index = i + w * j + w * h*k;
1678                 int src_index = k + c * i + c * w*j;
1679                 im.data[dst_index] = (float)data[src_index] / 255.;
1680             }
1681         }
1682     }
1683 }
1684