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

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

Changes to support storing on the server side of the HSV histogram calculations

File size: 14.2 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
11var hasLocalStorage = (typeof(Storage) !== "undefined"); // ****
12//var 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
134function createHSLHistogram(imageObj, quant)
135{
136 var i;
137
138 if (!$('#hsl_canvas').length) {
139 $('<canvas>', {id: 'hsl_canvas'}).hide().appendTo('body');
140 }
141
142 var imageData = drawImage(imageObj,'hsl_canvas');
143
144 var outputLength = quant * quant * quant;
145 var outputArray = new Array(outputLength);
146 for (i=0; i<outputLength; i++) {
147 outputArray[i] = 0;
148 }
149
150 var total = 0.0;
151
152 var log2 = Math.log(2);
153
154 //calculate value to shift by (log base 2)
155
156 var shift_sat = Math.floor(Math.log(quant)/log2);
157 var shift_hue = Math.floor(Math.log(quant*quant)/log2);
158
159 //console.log("bit-shift sat = " + shift_sat);
160 //console.log("bit-shift hue = " + shift_hue);
161
162 var data = imageData.data;
163
164 //Loop through each pixel
165 var y,p;
166 for (y=0,p=0; y<imageObj.height; y++) {
167 var x;
168 for (x=0; x<imageObj.width; x++,p+=4) {
169 // convert 4 byte data value into a colour pixel
170 var rgb_c = new RGBColour(data[p],data[p+1],data[p+2],data[p+3]/255.0);
171 var hsl = new rgb_c.getHSL();
172
173 // express h,s and b in the range 0..1
174
175 var h = hsl.h / 360.0;
176 var s = hsl.s / 100.0;
177 var b = hsl.l / 100.0;
178
179 var result = (Math.floor(h * (quant - 1)) << shift_hue)
180 | (Math.floor(s * (quant - 1)) << shift_sat)
181 | Math.floor(b * (quant - 1));
182
183 //number of opaque pixels
184 var count = hsl.a; // 'a' is naturally in the range 0..1
185
186 //add to the total number of opaque pixels
187 total += count;
188
189 //add the frequency of each colour to the histogram
190 outputArray[result] += count;
191 }
192 }
193
194 //Normalise the histogram, based on the number of opaque pixels
195 for (i=0; i<outputArray.length; i++) {
196 outputArray[i] = outputArray[i] / total;
197 }
198
199/*
200 if (saveOnServer) {
201 console.log("Saving HSV quantized histogram on server: " + imageObj.title)
202 //console.log("outputArray = " + JSON.stringify(outputArray));
203
204 var jsonFilename = imageObj.title + ".json";
205 var data = { jsonFilename: jsonFilename, jsonData: JSON.stringify(outputArray)};
206
207 console.log("Saving colour histogram data for " + imageObj.title);
208 $.ajax({
209 type: "POST",
210 url: "../similarity-2d/save-json-data.jsp",
211 data: data
212 });
213 }
214*/
215
216 return outputArray;
217}
218
219var flag_comparison_array = Array(2);
220var clicked_on_count = 0;
221
222function quantizedColourHistogramComparison(quant_colour_hist1,quant_colour_hist2)
223{
224 // Assumes both histograms are of the same length
225
226 var i;
227 var quant_product = 0.0;
228
229 //Loop through and compare the histograms
230 for (i=0; i<quant_colour_hist1.length; i++) {
231 //take the overlap
232 quant_product += Math.min(quant_colour_hist1[i], quant_colour_hist2[i]);
233
234 // consider replacing with abs for difference
235 }
236
237 alert("Product for HSL histogram: " + quant_product);
238
239}
240
241
242function displayFlags(img_list,$displayDiv,$progressArea,$progressBar)
243{
244 var img_list_len = img_list.length;
245
246 if (img_list_len==0) {
247 return;
248 }
249 else if (img_list_len>show_progress) {
250 $progressArea.slideDown();
251 }
252
253 img_list.sort();
254
255 var root_img_re = /^.*\/(.*?)\..*?$/;
256
257 var progress_step = 100.0 / img_list_len;
258
259 var callback_count = 0;
260
261 var i;
262 for (i=0; i<img_list.length; i++) {
263 var img_url = img_list[i];
264 var img_matches = root_img_re.exec(img_url);
265 var title = img_matches[1];
266
267 var imageObj = new Image();
268 imageObj.onload = function() {
269 callback_count++;
270 progressVal += progress_step;
271 $progressBar.progressbar('value',progressVal);
272
273 if (callback_count == img_list_len) {
274 if (img_list_len>show_progress) {
275 progressVal = 100;
276 $progressBar.progressbar('value',progressVal);
277 //$progressArea.slideUp();
278
279 // Now move on and start computing colour histograms
280 setTimeout(function()
281 { doneDisplayFlags(img_list,$progressArea,$progressBar); }
282 ,start_hist_delay);
283 }
284 }
285 };
286
287
288 /*
289$("h2").live('mousedown', function(e) {
290 if( (e.which == 1) ) {
291 alert("left button");
292 }if( (e.which == 3) ) {
293 alert("right button");
294 }else if( (e.which == 2) ) {
295 alert("middle button");
296 }
297 e.preventDefault();
298}).live('contextmenu', function(e){
299 e.preventDefault();
300});
301 */
302
303 imageObj.onclick = function(e) {
304 // Store result of HSL quantization in the image object/tag
305 if (!this.quantHSLHist) {
306 // Only need to compute this if it is not already stored in the object/tag
307 this.quantHSLHist = createHSLHistogram(this,16);
308 console.log(this.quantHSLHist);
309 }
310
311 if (e.which == 1 ) {
312 // Left => use in comparison pair
313 flag_comparison_array[clicked_on_count] = this.quantHSLHist;
314
315 clicked_on_count++;
316 if (clicked_on_count==2) {
317 // trigger comparison
318 quantizedColourHistogramComparison(flag_comparison_array[0],flag_comparison_array[1]);
319 clicked_on_count=0;
320 }
321 }
322 else if (e.which == 2) {
323 // Middle => fix on this and do similarity with everything else
324 var fix_id = this.id;
325 e.preventDefault();
326 }
327
328 };
329
330
331 imageObj.src = img_url;
332 imageObj.title = title;
333 imageObj.id = "flag-img-" + i;
334
335 $displayDiv.append(imageObj);
336 }
337}
338
339function computeFlagHistogramChain(chain_count, img_list_len,
340 progressVal, progress_step,
341 $progressArea,$progressBar)
342{
343 var flag_id = "flag-img-" + chain_count;
344 console.log("Processing Image ID: " + flag_id);
345 var imageObj = document.getElementById(flag_id);
346
347 if (!imageObj.quantHSLHist) {
348 // Only need to compute this if it is not
349 // already stored in the object/tag
350
351 if (retrieveFromServer) {
352 // see if it is stored on the server
353 console.log("Retrieving stored colour histogram for " + imageObj.title + " ...");
354 $.ajax({
355 async: false,
356 dataType: "json",
357 url: "../similarity-2d/json-data/" + imageObj.title + ".json",
358 success: function(data) {
359 console.log("... success");
360 // 'data' is the array of integer vals we want
361 imageObj.quantHSLHist = data;
362 },
363 error: function() {
364 console.log("... not stored on server");
365 // not stored on the server (currently)
366 // => need to compute it
367 imageObj.quantHSLHist = createHSLHistogram(imageObj,16);
368 //console.log(imageObj.quantHSLHist);
369
370 }
371 });
372 }
373 else {
374 imageObj.quantHSLHist = createHSLHistogram(imageObj,16);
375 }
376
377 }
378
379 if (chain_count < img_list_len-1) {
380 progressVal += progress_step;
381 $progressBar.progressbar('value',progressVal);
382
383 setTimeout(function()
384 { computeFlagHistogramChain(chain_count+1,img_list_len,
385 progressVal, progress_step,
386 $progressArea,$progressBar)
387 }
388 ,mini_delay // any time delay causes break in 'rendering' thread, even 0!
389 );
390
391 }
392 else {
393 $progressArea.find('span:first').text("Done.");
394 if (img_list_len>show_progress) {
395 progressVal = 100;
396 $progressBar.progressbar('value',progressVal);
397 $progressArea.slideUp();
398 }
399
400 doneComputingHistograms(img_list_len);
401 }
402}
403
404
405function computeFlagHistograms(img_list,$progressArea,$progressBar)
406{
407 var img_list_len = img_list.length;
408
409
410 if (img_list_len==0) {
411 $progressArea.find('span:first').text("Empty list: no computation needed.");
412 return;
413 }
414
415
416 $progressArea.find('span:first').text("Computing histograms:");
417 progressVal = 0;
418
419 if (img_list_len>show_progress) {
420 $progressArea.slideDown();
421 }
422
423 var progress_step = 100.0 / img_list_len;
424
425 // Start the chaining process
426 setTimeout(function()
427 { computeFlagHistogramChain(0,img_list_len,
428 progressVal, progress_step,
429 $progressArea,$progressBar)
430 }
431 ,mini_delay // any time delay causes break in 'rendering' thread, even 0!
432 );
433
434}
435
436function doneComputingHistograms(img_list_len)
437{
438 quantHSLHistogramArray = new Array(img_list_len);
439 for (var i=0; i<img_list_len; i++) {
440 var flag_id = "flag-img-" + i;
441 var imageObj = document.getElementById(flag_id);
442 quantHSLHistogramArray[i] = imageObj.quantHSLHist;
443 }
444 var json_hist_data = JSON.stringify(quantHSLHistogramArray);
445
446 if (hasLocalStorage) {
447 // build up quantHSLHistogramArray from all the images
448
449 console.log("Storing computed HSL histograms in localStorage");
450 localStorage.quantHSLHistogramArray = json_hist_data;
451 }
452
453 if (saveOnServer) {
454 // run-length encode data, so less to send
455 var quantHSLHistogramArrayRLE = new Array(img_list_len);
456 for (var i=0; i<img_list_len; i++) {
457 //console.log("rle encoding ... i = " + i);
458 quantHSLHistogramArrayRLE[i] = runlength_encode(quantHSLHistogramArray[i])
459
460 //var test_decode_array = runlength_decode(quantHSLHistogramArrayRLE[i]);
461 //console.log("Checking decoded array: " + arrays_identical(test_decode_array,quantHSLHistogramArray[i]));
462 }
463
464
465 var json_hist_data_rle = JSON.stringify(quantHSLHistogramArrayRLE);
466
467 var json_filename = "all-hsv-histograms-rle.json";
468 var data = { jsonFilename: json_filename, jsonData: json_hist_data_rle};
469
470 console.log("Saving colour histogram data for all flags");
471 $.ajax({
472 type: "POST",
473 url: "../similarity-2d/save-json-data.jsp",
474 data: data
475 });
476 }
477}
478
479function doneDisplayFlags(img_list,$progressArea,$progressBar)
480{
481 console.log("doneDisplayFlags()");
482
483 var needToComputeHistograms = true;
484
485 if (hasLocalStorage) {
486
487 if (localStorage.quantHSLHistogramArray) {
488
489 console.log("Retrieving quantized HSL histograms from local storage");
490
491 var stored_hist_array = JSON.parse(localStorage["quantHSLHistogramArray"]);
492 if (stored_hist_array.length == img_list.length) {
493 // Assume if the number of images process hasn't changed, then neither
494 // has the stored historgram values
495
496 quantHSLHistogramArray = stored_hist_array;
497
498 var i;
499 for (i=0; i<img_list.length; i++) {
500 var flag_id = "flag-img-" + i;
501 var imageObj = document.getElementById(flag_id);
502 imageObj.quantHSLHist = quantHSLHistogramArray[i];
503 }
504
505 needToComputeHistograms = false;
506 }
507 else {
508 console.log("Different number of images detected => regenerating");
509 }
510 }
511 }
512
513 if (needToComputeHistograms) {
514
515 if (retrieveFromServer) {
516 // before computing histograms from scratch, see if resulting data stored on server
517
518 console.log("Retrieving stored colour histgram data for all flags ...");
519 $.ajax({
520 async: true,
521 dataType: "json",
522 url: "../similarity-2d/json-data/all-hsv-histograms-rle.json",
523 success: function(rle_data) {
524 console.log("... success");
525 if (rle_data.length != img_list.length) {
526 console.log("Stored histogram data out of date with flag list.");
527 // what is stored on the sever differed to the number of images displayed
528 computeFlagHistograms(img_list,$progressArea,$progressBar);
529 }
530 else {
531 var img_list_len = img_list.length;
532 quantHSLHistogramArray = new Array(img_list_len);
533
534 // Need to rle decode each entry in this array
535 for (var i=0; i<img_list_len; i++) {
536 quantHSLHistogramArray[i] = runlength_decode(rle_data[i]);
537 var flag_id = "flag-img-" + i;
538 var imageObj = document.getElementById(flag_id);
539 imageObj.quantHSLHist = quantHSLHistogramArray[i];
540
541 }
542
543 needToComputeHistograms = false;
544
545 $progressArea.slideUp();
546 doneComputingHistograms(img_list.length);
547
548 }
549 },
550 error: function() {
551 console.log("... not stored on server");
552 computeFlagHistograms(img_list,$progressArea,$progressBar);
553 }
554 });
555
556
557 }
558 else {
559 computeFlagHistograms(img_list,$progressArea,$progressBar);
560 }
561 }
562 else {
563 $progressArea.slideUp();
564 doneComputingHistograms(img_list.length);
565 }
566}
567
568function rankBySimilarity(imageData,x_dim,y_dim)
569{
570 // quantizedColourHistogramComparison(quant_colour_hist1,quant_colour_hist2)
571
572}
Note: See TracBrowser for help on using the repository browser.