source: other-projects/nz-flag-design/trunk/similarity-2d/flag-processing.js@ 29806

Last change on this file since 29806 was 29806, checked in by davidb, 9 years ago

Initial version with ranked image similarity running

File size: 17.0 KB
Line 
1"use strict";
2
3var progressVal = 0;
4
5var show_progress = 5;
6
7var start_hist_delay = 1000; // used to be 4000
8var mini_delay = 300;
9
10
11//var hasLocalStorage = (typeof(Storage) !== "undefined"); // ****
12var hasLocalStorage = false;
13
14var quantHSLHistogramArray;
15
16//var saveOnServer=true;
17var saveOnServer=false;
18var retrieveFromServer=true;
19
20
21function runlength_encode(int_array) {
22
23 var array_len = int_array.length;
24
25 if (array_len<2) {
26 console.warn("runlength_encode(): unable to run-length encode array of length " + array_len);
27 console.warn("returning null");
28 return null;
29 }
30
31 var int_array_rle = new Array();
32
33
34 var lock_val=int_array[0];
35 var next_val=int_array[1];
36 var i = 1;
37
38 while (i<array_len) {
39 var c=1;
40 while (next_val==lock_val) {
41 c++;
42 var next_pos = i+c-1;
43 if (next_pos<array_len) {
44 next_val = int_array[next_pos];
45 }
46 else {
47 // hit end of array
48 break;
49 }
50 }
51 // come out of a run-length sequence of same val
52 // next_val is one past the run-length sequence
53
54 int_array_rle.push(c);
55 int_array_rle.push(lock_val);
56
57 i+=c;
58
59 if (i<array_len) {
60 lock_val = next_val;
61 next_val = int_array[i];
62 }
63 else {
64 break;
65 }
66 }
67
68 return int_array_rle;
69}
70
71
72
73function runlength_decode(int_array_rle) {
74
75 var array_rle_len = int_array_rle.length;
76
77 if (array_rle_len<2) {
78 console.warn("runlength_decode(): unable to run-length decode array of length " + array_rle_len);
79 console.warn("returning null");
80 return null;
81 }
82
83 var int_array = new Array();
84 for (var i=0; i<array_rle_len; i+=2){
85 var rep = int_array_rle[i];
86 var val = int_array_rle[i+1];
87 for (var r=0; r<rep; r++) {
88 int_array.push(val);
89 }
90 }
91
92 return int_array;
93}
94
95
96
97function arrays_identical(int_array1, int_array2) {
98
99 var array_len1 = int_array1.length;
100 var array_len2 = int_array2.length;
101
102 if (array_len1 != array_len2) {
103 console.warn("arrays_identical(): array lengths differ, array1("+array_len1+") vs array2(" + array_len2 + ")");
104 return false;
105 }
106
107 var all_ident = true;
108
109 for (var i=0; i<array_len1; i++){
110 if (int_array1[i] != int_array2[i]) {
111 all_ident = false;
112 break;
113 }
114 }
115
116 return all_ident;
117}
118
119
120function drawImage(imageObj, canvasId) {
121 var imgCanvas = document.getElementById(canvasId),
122 context, imageData, data,
123 imageX = 0, imageY = 0,
124 imageWidth = imageObj.width,
125 imageHeight = imageObj.height;
126
127 context = imgCanvas.getContext('2d');
128 context.drawImage(imageObj, imageX, imageY, imageWidth, imageHeight);
129 imageData = context.getImageData(imageX, imageY, imageWidth, imageHeight);
130
131 return imageData;
132}
133
134
135
136function createHSLHistogramFromCanvasData(imageData, imageWidth, imageHeight, quant)
137{
138 var i;
139
140 var outputLength = quant * quant * quant;
141 var outputArray = new Array(outputLength);
142 for (i=0; i<outputLength; i++) {
143 outputArray[i] = 0;
144 }
145
146 var total = 0.0;
147
148 var log2 = Math.log(2);
149
150 //calculate value to shift by (log base 2)
151
152 var shift_sat = Math.floor(Math.log(quant)/log2);
153 var shift_hue = Math.floor(Math.log(quant*quant)/log2);
154
155 //console.log("bit-shift sat = " + shift_sat);
156 //console.log("bit-shift hue = " + shift_hue);
157
158 var data = imageData.data;
159
160 //Loop through each pixel
161 var y,p;
162 for (y=0,p=0; y<imageHeight; y++) {
163 var x;
164 for (x=0; x<imageWidth; x++,p+=4) {
165 // convert 4 byte data value into a colour pixel
166 var rgb_c = new RGBColour(data[p],data[p+1],data[p+2],data[p+3]/255.0);
167 var hsl = new rgb_c.getHSL();
168
169 // express h,s and b in the range 0..1
170
171 var h = hsl.h / 360.0;
172 var s = hsl.s / 100.0;
173 var b = hsl.l / 100.0;
174
175 var result = (Math.floor(h * (quant - 1)) << shift_hue)
176 | (Math.floor(s * (quant - 1)) << shift_sat)
177 | Math.floor(b * (quant - 1));
178
179 //number of opaque pixels
180 var count = hsl.a; // 'a' is naturally in the range 0..1
181
182 //add to the total number of opaque pixels
183 total += count;
184
185 //add the frequency of each colour to the histogram
186 outputArray[result] += count;
187 }
188 }
189
190 if (total == 0) {
191 // entire image must have been blank
192 // make total '1' to stop NaN being generated
193 total = 1;
194 }
195
196 //Normalise the histogram, based on the number of opaque pixels
197 for (i=0; i<outputArray.length; i++) {
198 outputArray[i] = outputArray[i] / total;
199 }
200
201 return outputArray;
202}
203
204
205function createHSLHistogram(imageObj, quant)
206{
207 if (!$('#hsl_canvas').length) {
208 $('<canvas>', {id: 'hsl_canvas'}).hide().appendTo('body');
209 }
210
211 var imageData = drawImage(imageObj,'hsl_canvas');
212
213 var outputArray = createHSLHistogramFromCanvasData(imageData,imageObj.width,imageObj.height,quant);
214
215/*
216 if (saveOnServer) {
217 console.log("Saving HSV quantized histogram on server: " + imageObj.title.toLowerCase())
218 //console.log("outputArray = " + JSON.stringify(outputArray));
219
220 var jsonFilename = imageObj.title.toLowerCase() + ".json";
221 var data = { jsonFilename: jsonFilename, jsonData: JSON.stringify(outputArray)};
222
223 console.log("Saving colour histogram data for " + imageObj.title.toLowerCase());
224 $.ajax({
225 type: "POST",
226 url: "../similarity-2d/save-json-data.jsp",
227 data: data
228 });
229 }
230*/
231
232 return outputArray;
233}
234
235var flag_comparison_array = Array(2);
236var clicked_on_count = 0;
237
238function quantizedColourHistogramComparison(quant_colour_hist1,quant_colour_hist2)
239{
240 // Assumes both histograms are of the same length
241
242 var i;
243 var quant_product = 0.0;
244
245 //Loop through and compare the histograms
246 for (i=0; i<quant_colour_hist1.length; i++) {
247 //take the overlap
248 quant_product += Math.min(quant_colour_hist1[i], quant_colour_hist2[i]);
249
250 // consider replacing with abs for difference
251 }
252
253 console.log("Product for HSL histogram: " + quant_product);
254
255 return quant_product;
256}
257
258
259function displayFlags(img_list,$displayDiv,$progressArea,$progressBar)
260{
261 var img_list_len = img_list.length;
262
263 if (img_list_len==0) {
264 return;
265 }
266 else if (img_list_len>show_progress) {
267 $progressArea.slideDown();
268 }
269
270 img_list.sort();
271
272 var root_img_re = /^.*\/(.*?)\..*?$/;
273
274 var progress_step = 100.0 / img_list_len;
275
276 var callback_count = 0;
277
278 var i;
279 for (i=0; i<img_list.length; i++) {
280 var img_url = img_list[i];
281 var img_matches = root_img_re.exec(img_url);
282 var title = img_matches[1];
283
284 var imageObj = new Image();
285 imageObj.onload = function() {
286 callback_count++;
287 progressVal += progress_step;
288 $progressBar.progressbar('value',progressVal);
289
290 if (callback_count == img_list_len) {
291 if (img_list_len>show_progress) {
292 progressVal = 100;
293 $progressBar.progressbar('value',progressVal);
294 //$progressArea.slideUp();
295
296 // Now move on and start computing colour histograms
297 setTimeout(function()
298 { doneDisplayFlags(img_list,$progressArea,$progressBar); }
299 ,start_hist_delay);
300 }
301 }
302 };
303
304
305 /*
306$("h2").live('mousedown', function(e) {
307 if( (e.which == 1) ) {
308 alert("left button");
309 }if( (e.which == 3) ) {
310 alert("right button");
311 }else if( (e.which == 2) ) {
312 alert("middle button");
313 }
314 e.preventDefault();
315}).live('contextmenu', function(e){
316 e.preventDefault();
317});
318 */
319
320 imageObj.onclick = function(e) {
321 // Store result of HSL quantization in the image object/tag
322 if (!this.quantHSLHist) {
323 // Only need to compute this if it is not already stored in the object/tag
324 this.quantHSLHist = createHSLHistogram(this,16);
325 console.log(this.quantHSLHist);
326 }
327
328 if (e.which == 1 ) {
329 // Left => use in comparison pair
330 flag_comparison_array[clicked_on_count] = this.quantHSLHist;
331
332 clicked_on_count++;
333 if (clicked_on_count==2) {
334 // trigger comparison
335 alert("Similarity score: " + quantizedColourHistogramComparison(flag_comparison_array[0],flag_comparison_array[1]));
336 clicked_on_count=0;
337 }
338 }
339 else if (e.which == 2) {
340 // Middle => fix on this and do similarity with everything else
341 var fix_id = this.id;
342 e.preventDefault();
343 }
344
345 };
346
347
348 imageObj.src = img_url;
349 imageObj.title = title.toUpperCase();
350 imageObj.country = imageObj.title;
351 imageObj.id = "flag-img-" + i;
352
353 $displayDiv.append(imageObj);
354 }
355}
356
357
358
359
360
361function calcSimilarityValues(newFlagQuantHSLHist, $displayDiv,$progressArea,$progressBar)
362{
363 console.log("*** calcSimilarityValues()");
364
365 var iframe = $('#similarity-2d-iframe').contents();
366
367 var img_obj_list = iframe.find('#flagArea').children('img').toArray();
368
369 var img_obj_list_len = img_obj_list.length;
370
371 if (img_obj_list_len==0) {
372 return;
373 }
374 else if (img_obj_list_len>show_progress) {
375 // number of images to process non-trivial
376 $progressArea.slideDown();
377 }
378
379 var progress_step = 100.0 / img_obj_list_len;
380
381 for (var i=0; i<img_obj_list.length; i++) {
382 var imgObj = img_obj_list[i];
383
384 var existingQuantHSLHist = imgObj.quantHSLHist;
385
386 var similarity_score = quantizedColourHistogramComparison(newFlagQuantHSLHist,existingQuantHSLHist);
387 imgObj.similarityScore = similarity_score;
388 imgObj.title = imgObj.country + ", Similarity score: " + similarity_score;
389
390 progressVal += progress_step;
391 console.log("*** i = " + i);
392 console.log("*** pbar = " + $progressBar.progressbar);
393 if ($progressBar.progressbar) {
394 $progressBar.progressbar('value',progressVal);
395 }
396 }
397
398 //progressVal = 100;
399 //$progressBar.progressbar('value',progressVal);
400
401 if (img_obj_list_len>show_progress) {
402 $progressArea.slideUp();
403 }
404}
405
406function sortUsingAttribute(parent, childSelector, field) {
407 var items = parent.children(childSelector).sort(function(a, b) {
408 var vA = a.attr(field);
409 var vB = b.attr(field)
410 return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
411 });
412
413 parent.empty(childSelecctor);
414 parent.append(items);
415}
416
417
418function compareSimilarityValue(a,b) {
419
420 //var vA = a.similarityScore;
421 //var vB = b.similarityScore;
422 //return (vA < vB) ? -1 : (vA > vB) ? 1 : 0;
423
424 return (b.similarityScore - a.similarityScore);
425}
426
427function sortFlagsBySimilarityValue($iframe)
428{
429 var img_obj_list = $iframe.find('#flagArea > img').toArray();
430
431 var sorted_img_obj_list = img_obj_list.sort(compareSimilarityValue);
432 //console.log("*** sorted img len = " + sorted_img_obj_list.length);
433
434 $iframe.find('#flagArea').empty('img');
435
436 $iframe.find('#flagArea').append(sorted_img_obj_list);
437
438 //sortUsingAttribute('#flagArea','img','similarityValue');
439}
440
441
442
443function computeFlagHistogramChain(chain_count, img_list_len,
444 progressVal, progress_step,
445 $progressArea,$progressBar)
446{
447 var flag_id = "flag-img-" + chain_count;
448 console.log("Processing Image ID: " + flag_id);
449 var imageObj = document.getElementById(flag_id);
450
451 if (!imageObj.quantHSLHist) {
452 // Only need to compute this if it is not
453 // already stored in the object/tag
454
455 if (retrieveFromServer) {
456 // see if it is stored on the server
457 console.log("Retrieving stored colour histogram for " + imageObj.title.toLowerCase() + " ...");
458 $.ajax({
459 async: false,
460 dataType: "json",
461 url: "../similarity-2d/json-data/" + imageObj.title.toLowerCase() + ".json",
462 success: function(data) {
463 console.log("... success");
464 // 'data' is the array of integer vals we want
465 imageObj.quantHSLHist = data;
466 },
467 error: function() {
468 console.log("... not stored on server");
469 // not stored on the server (currently)
470 // => need to compute it
471 imageObj.quantHSLHist = createHSLHistogram(imageObj,16);
472 //console.log(imageObj.quantHSLHist);
473
474 }
475 });
476 }
477 else {
478 imageObj.quantHSLHist = createHSLHistogram(imageObj,16);
479 }
480
481 }
482
483 if (chain_count < img_list_len-1) {
484 progressVal += progress_step;
485 $progressBar.progressbar('value',progressVal);
486
487 setTimeout(function()
488 { computeFlagHistogramChain(chain_count+1,img_list_len,
489 progressVal, progress_step,
490 $progressArea,$progressBar)
491 }
492 ,mini_delay // any time delay causes break in 'rendering' thread, even 0!
493 );
494
495 }
496 else {
497 $progressArea.find('span:first').text("Done.");
498 if (img_list_len>show_progress) {
499 progressVal = 100;
500 $progressBar.progressbar('value',progressVal);
501 $progressArea.slideUp();
502 }
503
504 doneComputingHistograms(img_list_len);
505 }
506}
507
508
509function computeFlagHistograms(img_list,$progressArea,$progressBar)
510{
511 var img_list_len = img_list.length;
512
513
514 if (img_list_len==0) {
515 $progressArea.find('span:first').text("Empty list: no computation needed.");
516 return;
517 }
518
519
520 $progressArea.find('span:first').text("Computing histograms:");
521 progressVal = 0;
522
523 if (img_list_len>show_progress) {
524 $progressArea.slideDown();
525 }
526
527 var progress_step = 100.0 / img_list_len;
528
529 // Start the chaining process
530 setTimeout(function()
531 { computeFlagHistogramChain(0,img_list_len,
532 progressVal, progress_step,
533 $progressArea,$progressBar)
534 }
535 ,mini_delay // any time delay causes break in 'rendering' thread, even 0!
536 );
537
538}
539
540function doneComputingHistograms(img_list_len)
541{
542 quantHSLHistogramArray = new Array(img_list_len);
543 for (var i=0; i<img_list_len; i++) {
544 var flag_id = "flag-img-" + i;
545 var imageObj = document.getElementById(flag_id);
546 quantHSLHistogramArray[i] = imageObj.quantHSLHist;
547 }
548 var json_hist_data = JSON.stringify(quantHSLHistogramArray);
549
550 if (hasLocalStorage) {
551 // build up quantHSLHistogramArray from all the images
552
553 console.log("Storing computed HSL histograms in localStorage");
554 localStorage.quantHSLHistogramArray = json_hist_data;
555 }
556
557 if (saveOnServer) {
558 // run-length encode data, so less to send
559 var quantHSLHistogramArrayRLE = new Array(img_list_len);
560 for (var i=0; i<img_list_len; i++) {
561 //console.log("rle encoding ... i = " + i);
562 quantHSLHistogramArrayRLE[i] = runlength_encode(quantHSLHistogramArray[i])
563
564 //var test_decode_array = runlength_decode(quantHSLHistogramArrayRLE[i]);
565 //console.log("Checking decoded array: " + arrays_identical(test_decode_array,quantHSLHistogramArray[i]));
566 }
567
568
569 var json_hist_data_rle = JSON.stringify(quantHSLHistogramArrayRLE);
570
571 var json_filename = "all-hsv-histograms-rle.json";
572 var data = { jsonFilename: json_filename, jsonData: json_hist_data_rle};
573
574 console.log("Saving colour histogram data for all flags");
575 $.ajax({
576 type: "POST",
577 url: "../similarity-2d/save-json-data.jsp",
578 data: data
579 });
580 }
581}
582
583function doneDisplayFlags(img_list,$progressArea,$progressBar)
584{
585 console.log("doneDisplayFlags()");
586
587 var needToComputeHistograms = true;
588
589 if (hasLocalStorage) {
590
591 if (localStorage.quantHSLHistogramArray) {
592
593 console.log("Retrieving quantized HSL histograms from local storage");
594
595 var stored_hist_array = JSON.parse(localStorage["quantHSLHistogramArray"]);
596 if (stored_hist_array.length == img_list.length) {
597 // Assume if the number of images process hasn't changed, then neither
598 // has the stored historgram values
599
600 quantHSLHistogramArray = stored_hist_array;
601
602 var i;
603 for (i=0; i<img_list.length; i++) {
604 var flag_id = "flag-img-" + i;
605 var imageObj = document.getElementById(flag_id);
606 imageObj.quantHSLHist = quantHSLHistogramArray[i];
607 }
608
609 needToComputeHistograms = false;
610 }
611 else {
612 console.log("Different number of images detected => regenerating");
613 }
614 }
615 }
616
617 if (needToComputeHistograms) {
618
619 if (retrieveFromServer) {
620 // before computing histograms from scratch, see if resulting data stored on server
621
622 console.log("Retrieving stored colour histgram data for all flags ...");
623 $.ajax({
624 async: true,
625 dataType: "json",
626 url: "../similarity-2d/json-data/all-hsv-histograms-rle.json",
627 success: function(rle_data) {
628 console.log("... success");
629 if (rle_data.length != img_list.length) {
630 console.log("Stored histogram data out of date with flag list.");
631 console.log("rle len = " + rle_data.length + ", img_list len = " + img_list.length);
632 // what is stored on the sever differed to the number of images displayed
633 computeFlagHistograms(img_list,$progressArea,$progressBar);
634 }
635 else {
636 var img_list_len = img_list.length;
637 quantHSLHistogramArray = new Array(img_list_len);
638
639 // Need to rle decode each entry in this array
640 for (var i=0; i<img_list_len; i++) {
641 quantHSLHistogramArray[i] = runlength_decode(rle_data[i]);
642 var flag_id = "flag-img-" + i;
643 var imageObj = document.getElementById(flag_id);
644 imageObj.quantHSLHist = quantHSLHistogramArray[i];
645
646 }
647
648 needToComputeHistograms = false;
649
650 $progressArea.slideUp();
651 doneComputingHistograms(img_list.length);
652
653 }
654 },
655 error: function() {
656 console.log("... not stored on server");
657 computeFlagHistograms(img_list,$progressArea,$progressBar);
658 }
659 });
660
661
662 }
663 else {
664 computeFlagHistograms(img_list,$progressArea,$progressBar);
665 }
666 }
667 else {
668 $progressArea.slideUp();
669 doneComputingHistograms(img_list.length);
670 }
671}
672
673function rankBySimilarity(imageData,x_dim,y_dim)
674{
675 // quantizedColourHistogramComparison(quant_colour_hist1,quant_colour_hist2)
676
677}
Note: See TracBrowser for help on using the repository browser.