-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimgdb.cpp
1482 lines (1175 loc) · 44.2 KB
/
imgdb.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/******************************************************************************
imgSeek :: C++ database implementation
---------------------------------------
begin : Fri Jan 17 2003
email : nieder|at|mail.ru
Copyright (C) 2003-2009 Ricardo Niederberger Cabral
Clean-up and speed-ups by Geert Janssen <geert at ieee.org>, Jan 2006:
- removed lots of dynamic memory usage
- SigStruct now holds only static data
- db save and load much faster
- made Qt image reading faster using scanLine()
- simpler imgBin initialization
- corrected pqResults calculation; did not get best scores
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
******************************************************************************/
/* C Includes */
#include <ctime>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/* STL Includes */
#include <fstream>
#include <iostream>
using namespace std;
/* ImageMagick includes */
#include <magick/api.h>
//using namespace Magick;
/* imgSeek includes */
/* Database */
#include "bloom_filter.h"
#include "imgdb.h"
#ifdef ISK_SWIG_JAVA
/* Java interface */
#include "imgdb_wrap.h"
#else
/* Python interface */
// #include "imgdb_python_wrap.h"
// #ifdef _WINDOWS
// #include "imgdb_python_wrap.h"
// #else
// #include "imgdb_python_linux_wrap.h"
// #endif
#endif
// Globals
dbSpaceMapType dbSpace;
keywordsMapType globalKwdsMap;
/* Fixed weight mask for pixel positions (i,j).
Each entry x = i*NUM_PIXELS + j, gets value max(i,j) saturated at 5.
To be treated as a constant.
*/
unsigned char imgBin[16384];
int imgBinInited = 0;
// Macros
#define validate_dbid(dbId) (dbSpace.count(dbId))
#define validate_imgid(dbId, imgId) (dbSpace.count(dbId) && (dbSpace[dbId]->sigs.count(imgId)))
void initImgBin()
{
imgBinInited = 1;
srand((unsigned)time(0));
/* setup initial fixed weights that each coefficient represents */
int i, j;
/*
0 1 2 3 4 5 6 i
0 0 1 2 3 4 5 5
1 1 1 2 3 4 5 5
2 2 2 2 3 4 5 5
3 3 3 3 3 4 5 5
4 4 4 4 4 4 5 5
5 5 5 5 5 5 5 5
5 5 5 5 5 5 5 5
j
*/
/* Every position has value 5, */
memset(imgBin, 5, NUM_PIXELS_SQUARED);
/* Except for the 5 by 5 upper-left quadrant: */
for (i = 0; i < 5; i++)
for (j = 0; j < 5; j++)
imgBin[i * 128 + j] = max(i, j);
// Note: imgBin[0] == 0
}
void initDbase(const int dbId) {
/* should be called before adding images */
if (!imgBinInited) initImgBin();
if (dbSpace.count(dbId)) { // db id already used?
cerr << "ERROR: dbId already in use" << endl;
return;
}
dbSpace[dbId] = new dbSpaceStruct();
}
void closeDbase() {
/* should be called before exiting app */
for (dpspaceIterator it = dbSpace.begin(); it != dbSpace.end(); it++) {
resetdb((*it).first);
delete (*it).second;
}
}
int getImageWidth(const int dbId, long int id) {
if (!validate_imgid(dbId, id)) { cerr << "ERROR: image id (" << id << ") not found on given dbid (" << dbId << ") or dbid not existant" << endl ; return 0;};
return dbSpace[dbId]->sigs[id]->width;
}
bool isImageOnDB(const int dbId, long int id) {
return dbSpace[dbId]->sigs.count(id) > 0;
}
int getImageHeight(const int dbId, long int id) {
if (!validate_imgid(dbId, id)) { cerr << "ERROR: image id (" << id << ") not found on given dbid (" << dbId << ") or dbid not existant" << endl ; return 0;};
return dbSpace[dbId]->sigs[id]->height;
}
double_vector getImageAvgl(const int dbId, long int id) {
double_vector res;
if (!dbSpace[dbId]->sigs.count(id))
return res;
for(int i=0;i<3; i++) {
res.push_back(dbSpace[dbId]->sigs[id]->avgl[i]);
}
return res;
}
int addImageFromImage(const int dbId, const long int id, Image * image ) {
/* id is a unique image identifier
filename is the image location
thname is the thumbnail location for this image
doThumb should be set to 1 if you want to save the thumbnail on thname
Images with a dimension smaller than ignDim are ignored
*/
if (image == (Image *) NULL) {
cerr << "ERROR: unable to add null image" << endl;
return 0;
}
// Made static for speed; only used locally
static Unit cdata1[16384];
static Unit cdata2[16384];
static Unit cdata3[16384];
int i;
int width, height;
ExceptionInfo exception;
Image *resize_image;
/*
Initialize the image info structure and read an image.
*/
GetExceptionInfo(&exception);
width = image->columns;
height = image->rows;
resize_image = SampleImage(image, 128, 128, &exception);
DestroyImage(image);
DestroyExceptionInfo(&exception);
if (resize_image == (Image *) NULL) {
cerr << "ERROR: unable to resize image" << endl;
return 0;
}
// store color value for basic channels
unsigned char rchan[16384];
unsigned char gchan[16384];
unsigned char bchan[16384];
GetExceptionInfo(&exception);
const PixelPacket *pixel_cache = AcquireImagePixels(resize_image, 0, 0, 128, 128, &exception);
for (int idx = 0; idx < 16384; idx++) {
rchan[idx] = pixel_cache->red;
gchan[idx] = pixel_cache->green;
bchan[idx] = pixel_cache->blue;
pixel_cache++;
}
DestroyImage(resize_image);
transformChar(rchan, gchan, bchan, cdata1, cdata2, cdata3);
DestroyExceptionInfo(&exception);
SigStruct *nsig = new SigStruct();
nsig->id = id;
nsig->width = width;
nsig->height = height;
if (dbSpace[dbId]->sigs.count(id)) {
delete dbSpace[dbId]->sigs[id];
dbSpace[dbId]->sigs.erase(id);
cerr << "ERROR: dbId already in use" << endl;
return 0;
}
// insert into sigmap
dbSpace[dbId]->sigs[id] = nsig;
// insert into ids bloom filter
dbSpace[dbId]->imgIdsFilter->insert(id);
calcHaar(cdata1, cdata2, cdata3,
nsig->sig1, nsig->sig2, nsig->sig3, nsig->avgl);
for (i = 0; i < NUM_COEFS; i++) { // populate buckets
#ifdef FAST_POW_GEERT
int x, t;
// sig[i] never 0
int x, t;
x = nsig->sig1[i];
t = (x < 0); /* t = 1 if x neg else 0 */
/* x - 0 ^ 0 = x; i - 1 ^ 0b111..1111 = 2-compl(x) = -x */
x = (x - t) ^ -t;
dbSpace[dbId]->imgbuckets[0][t][x].push_back(id);
x = nsig->sig2[i];
t = (x < 0);
x = (x - t) ^ -t;
dbSpace[dbId]->imgbuckets[1][t][x].push_back(id);
x = nsig->sig3[i];
t = (x < 0);
x = (x - t) ^ -t;
dbSpace[dbId]->imgbuckets[2][t][x].push_back(id);
should not fail
#else //FAST_POW_GEERT
//long_array3 imgbuckets = dbSpace[dbId]->imgbuckets;
if (nsig->sig1[i]>0) dbSpace[dbId]->imgbuckets[0][0][nsig->sig1[i]].push_back(id);
if (nsig->sig1[i]<0) dbSpace[dbId]->imgbuckets[0][1][-nsig->sig1[i]].push_back(id);
if (nsig->sig2[i]>0) dbSpace[dbId]->imgbuckets[1][0][nsig->sig2[i]].push_back(id);
if (nsig->sig2[i]<0) dbSpace[dbId]->imgbuckets[1][1][-nsig->sig2[i]].push_back(id);
if (nsig->sig3[i]>0) dbSpace[dbId]->imgbuckets[2][0][nsig->sig3[i]].push_back(id);
if (nsig->sig3[i]<0) dbSpace[dbId]->imgbuckets[2][1][-nsig->sig3[i]].push_back(id);
#endif //FAST_POW_GEERT
}
// success after all
return 1;
}
int addImageBlob(const int dbId, const long int id, const void *blob, const long length) {
ExceptionInfo exception;
ImageInfo *image_info;
image_info = CloneImageInfo((ImageInfo *) NULL);
Image *image = BlobToImage(image_info, blob, length, &exception);
if (exception.severity != UndefinedException) CatchException(&exception);
DestroyImageInfo(image_info);
return addImageFromImage(dbId, id, image);
}
int addImage(const int dbId, const long int id, char *filename) {
if (dbSpace[dbId]->sigs.count(id)) { // image already in db
return 0;
}
ExceptionInfo exception;
GetExceptionInfo(&exception);
ImageInfo *image_info;
image_info = CloneImageInfo((ImageInfo *) NULL);
(void) strcpy(image_info->filename, filename);
Image *image = ReadImage(image_info, &exception);
if (exception.severity != UndefinedException) CatchException(&exception);
DestroyImageInfo(image_info);
DestroyExceptionInfo(&exception);
if (image == (Image *) NULL) {
cerr << "ERROR: unable to read image" << endl;
return 0;
}
return addImageFromImage(dbId, id, image);
}
int loaddbfromstream(const int dbId, std::ifstream& f, srzMetaDataStruct& md) {
if (!dbSpace.count(dbId)) { // haven't been inited yet
initDbase(dbId);
} else { // already exists, so reset first
resetdb(dbId);
}
long int id;
int sz;
// read buckets
for (int c = 0; c < 3; c++)
for (int pn = 0; pn < 2; pn++)
for (int i = 0; i < 16384; i++) {
f.read((char *) &(sz), sizeof(int));
for (int k = 0; k < sz; k++) {
f.read((char *) &(id), sizeof(long int));
dbSpace[dbId]->imgbuckets[c][pn][i].push_back(id);
}
}
// read sigs
sigMap::size_type szt;
f.read((char *) &(szt), sizeof(sigMap::size_type));
if (md.iskVersion < SRZ_V0_6_0) {
cout << "INFO migrating database from a version prior to 0.6" << endl;
// read sigs
for (int k = 0; k < szt; k++) {
sigStructV06* nsig06 = new sigStructV06();
f.read((char *) nsig06, sizeof(sigStructV06));
SigStruct* nsig = new SigStruct(nsig06);
dbSpace[dbId]->sigs[nsig->id]=nsig;
}
return 1;
} else { // current version
DiskSigStruct* ndsig = new DiskSigStruct();
for (int k = 0; k < szt; k++) {
f.read((char *) ndsig, sizeof(DiskSigStruct));
SigStruct* nsig = new SigStruct(ndsig);
// insert new sig
dbSpace[dbId]->sigs[nsig->id]=nsig;
// insert into ids bloom filter
dbSpace[dbId]->imgIdsFilter->insert(nsig->id);
// read kwds
int kwid;
int szk;
f.read((char *) &(szk), sizeof(int));
for (int ki = 0; ki < szk; ki++) {
f.read((char *) &(kwid), sizeof(int));
nsig->keywords.insert(kwid);
// populate keyword postings
getKwdPostings(kwid)->imgIdsFilter->insert(nsig->id);
}
}
delete ndsig;
return 1;
}
}
srzMetaDataStruct loadGlobalSerializationMetadata(std::ifstream& f) {
srzMetaDataStruct md;
// isk version
f.read((char *) &(md.iskVersion), sizeof(int));
// binding language
f.read((char *) &(md.bindingLang), sizeof(int));
// trial or full
if (md.iskVersion < SRZ_V0_7_0) {
f.read((char *) &(md.isTrial), sizeof(int));
}
// platform
f.read((char *) &(md.compilePlat), sizeof(int));
// ok, I have some valid metadata
md.isValidMetadata = 1;
return md;
}
int loaddb(const int dbId, char *filename) {
std::ifstream f(filename, ios::binary);
if (!f.is_open()) {
cerr << "ERROR: unable to open file for read ops:" << filename << endl;
return 0;
}
int isMetadata = f.peek();
srzMetaDataStruct md;
md.isValidMetadata = 0;
if (isMetadata == SRZ_VERSIONED) { // has metadata
f.read((char *) &(isMetadata), sizeof(int));
md = loadGlobalSerializationMetadata(f);
}
int res = loaddbfromstream(dbId, f, md);
f.close();
return res;
}
int loadalldbs(char* filename) {
std::ifstream f(filename, ios::binary);
if (!f.is_open()) { // file not found, perhaps its the first start
return 0;
}
int isMetadata = f.peek();
srzMetaDataStruct md;
md.isValidMetadata = 0;
if (isMetadata == SRZ_VERSIONED) {// has metadata
f.read((char *) &(isMetadata), sizeof(int));
if (isMetadata != SRZ_VERSIONED) {
cerr << "ERROR: peek diff read" << endl;
return 0;
}
md = loadGlobalSerializationMetadata(f);
}
int dbId = 1;
int res = 0;
int sz = 0;
f.read((char *) &(sz), sizeof(int)); // number of dbs
for (int k = 0; k < sz; k++) { // for each db
f.read((char *) &(dbId), sizeof(int)); // db id
res += loaddbfromstream(dbId, f, md);
}
f.close();
return res;
}
int savedbtostream(const int dbId, std::ofstream& f) {
/*
Serialization order:
for each color {0,1,2}:
for {positive,negative}:
for each 128x128 coefficient {0-16384}:
[int] bucket size (size of list of ids)
for each id:
[long int] image id
[int] number of images (signatures)
for each image:
[long id] image id
for each sig coef {0-39}: (the NUM_COEFS greatest coefs)
for each color {0,1,2}:
[int] coef index (signed)
for each color {0,1,2}:
[double] average luminance
[int] image width
[int] image height
*/
int sz;
long int id;
if (!validate_dbid(dbId)) { cerr << "ERROR: database space not found (" << dbId << ")" << endl; return 0;}
// save buckets
for (int c = 0; c < 3; c++) {
for (int pn = 0; pn < 2; pn++) {
for (int i = 0; i < 16384; i++) {
sz = dbSpace[dbId]->imgbuckets[c][pn][i].size();
f.write((char *) &(sz), sizeof(int));
long_listIterator end = dbSpace[dbId]->imgbuckets[c][pn][i].end();
for (long_listIterator it = dbSpace[dbId]->imgbuckets[c][pn][i].begin(); it != end; it++) {
f.write((char *) &((*it)), sizeof(long int));
}
}
}
}
// save sigs
sigMap::size_type szt = dbSpace[dbId]->sigs.size();
f.write((char *) &(szt), sizeof(sigMap::size_type));
for (sigIterator it = dbSpace[dbId]->sigs.begin(); it != dbSpace[dbId]->sigs.end(); it++) {
id = (*it).first;
SigStruct* sig = (SigStruct*) (it->second);
DiskSigStruct dsig(*sig);
f.write((char *) (&dsig), sizeof(DiskSigStruct));
//// keywords
int_hashset& kwds = sig->keywords;
sz = kwds.size();
// number of keywords
f.write((char *) &(sz), sizeof(int));
// dump keywds
int kwid;
for (int_hashset::iterator itkw = kwds.begin(); itkw != kwds.end(); itkw++) {
kwid = *itkw;
f.write((char *) &(kwid), sizeof(int));
}
}
return 1;
}
void saveGlobalSerializationMetadata(std::ofstream& f) {
int wval;
// is versioned
wval = SRZ_VERSIONED;
f.write((char*)&(wval), sizeof(int));
// isk version
wval = SRZ_CUR_VERSION;
f.write((char*)&(wval), sizeof(int));
// binding language
#ifdef ISK_SWIG_JAVA
wval = SRZ_LANG_JAVA;
f.write((char*)&(wval), sizeof(int));
#else
wval = SRZ_LANG_PYTHON;
f.write((char*)&(wval), sizeof(int));
#endif
// platform
#ifdef _WINDOWS
wval = SRZ_PLAT_WINDOWS;
f.write((char*)&(wval), sizeof(int));
#else
wval = SRZ_PLAT_LINUX;
f.write((char*)&(wval), sizeof(int));
#endif
}
int savedb(const int dbId, char *filename) {
std::ofstream f(filename, ios::binary);
if (!f.is_open()) {
cerr << "ERROR: error opening file for write ops" << endl;
return 0;
}
saveGlobalSerializationMetadata(f);
int res = savedbtostream( dbId, f);
f.close();
return res;
}
int savealldbs(char* filename) {
std::ofstream f(filename, ios::binary);
if (!f.is_open()) {
cerr << "ERROR: error opening file for write ops" << endl;
return 0;
}
saveGlobalSerializationMetadata(f);
int res = 0;
int sz = dbSpace.size();
f.write((char *) &(sz), sizeof(int)); // num dbs
int dbId;
for (dpspaceIterator it = dbSpace.begin(); it != dbSpace.end(); it++) {
dbId = (*it).first;
f.write((char *) &(dbId), sizeof(int)); // db id
res += savedbtostream( dbId, f);
}
f.close();
return res;
}
std::vector<double> queryImgDataFiltered(const int dbId, Idx * sig1, Idx * sig2, Idx * sig3, double *avgl, int numres, int sketch, bloom_filter* bfilter) {
int idx, c;
int pn;
Idx *sig[3] = { sig1, sig2, sig3 };
if (bfilter) { // make sure images not on filter are penalized
for (sigIterator sit = dbSpace[dbId]->sigs.begin(); sit != dbSpace[dbId]->sigs.end(); sit++) {
if (!bfilter->contains((*sit).first)) { // image doesnt have keyword, just give it a terrible score
(*sit).second->score = 99999999;
} else { // ok, image content should be taken into account
(*sit).second->score = 0;
for (c = 0; c < 3; c++) {
(*sit).second->score += weights[sketch][0][c] * fabs((*sit).second->avgl[c] - avgl[c]);
}
}
}
delete bfilter;
} else { // search all images
for (sigIterator sit = dbSpace[dbId]->sigs.begin(); sit != dbSpace[dbId]->sigs.end(); sit++) {
(*sit).second->score = 0;
for (c = 0; c < 3; c++) {
(*sit).second->score += weights[sketch][0][c] * fabs((*sit).second->avgl[c] - avgl[c]);
}
}
}
for (int b = 0; b < NUM_COEFS; b++) { // for every coef on a sig
for (c = 0; c < 3; c++) {
//TODO see if FAST_POW_GEERT gives the same results
#ifdef FAST_POW_GEERT
pn = sig[c][b] < 0;
idx = (sig[c][b] - pn) ^ -pn;
#else
pn = 0;
if (sig[c][b]>0) {
pn = 0;
idx = sig[c][b];
} else {
pn = 1;
idx = -sig[c][b];
}
#endif
// update the score of every image which has this coef
long_listIterator end = dbSpace[dbId]->imgbuckets[c][pn][idx].end();
for (long_listIterator uit = dbSpace[dbId]->imgbuckets[c][pn][idx].begin();
uit != end; uit++) {
dbSpace[dbId]->sigs[(*uit)]->score -= weights[sketch][imgBin[idx]][c];
}
}
}
sigPriorityQueue pqResults; /* results priority queue; largest at top */
sigIterator sit = dbSpace[dbId]->sigs.begin();
vector<double> V;
// Fill up the numres-bounded priority queue (largest at top):
for (int cnt = 0; cnt < numres; cnt++) {
if (sit == dbSpace[dbId]->sigs.end()) {
// No more images; cannot get requested numres, so just return these initial ones.
return V;
}
pqResults.push(*(*sit).second);
sit++;
}
for (; sit != dbSpace[dbId]->sigs.end(); sit++) {
// only consider if not ignored due to keywords and if is a better match than the current worst match
if (((*sit).second->score < 99999) && ((*sit).second->score < pqResults.top().score)) {
// Make room by dropping largest entry:
pqResults.pop();
// Insert new entry:
pqResults.push(*(*sit).second);
}
}
SigStruct curResTmp; /* current result waiting to be returned */
while (pqResults.size()) {
curResTmp = pqResults.top();
pqResults.pop();
if (curResTmp.score < 99999) {
V.insert(V.end(), curResTmp.id);
V.insert(V.end(), curResTmp.score);
}
}
return V;
}
/* sig1,2,3 are int arrays of length NUM_COEFS
avgl is the average luminance
numres is the max number of results
sketch (0 or 1) tells which set of weights to use
*/
std::vector<double> queryImgData(const int dbId, Idx * sig1, Idx * sig2, Idx * sig3, double *avgl, int numres, int sketch) {
return queryImgDataFiltered(dbId, sig1, sig2, sig3, avgl, numres, sketch, 0);
}
/* Will only look at avg lum
* sig1,2,3 are int arrays of length NUM_COEFS
avgl is the average luminance
numres is the max number of results
sketch (0 or 1) tells which set of weights to use
*/
std::vector<double> queryImgDataFast(const int dbId, Idx * sig1, Idx * sig2, Idx * sig3, double *avgl, int numres, int sketch) {
int c;
vector<double> V;
if (!validate_dbid(dbId)) { cerr << "ERROR: database space not found (" << dbId << ")" << endl; return V;}
for (sigIterator sit = dbSpace[dbId]->sigs.begin(); sit != dbSpace[dbId]->sigs.end(); sit++) {
(*sit).second->score = 0;
for (c = 0; c < 3; c++) {
(*sit).second->score += weights[sketch][0][c]
* fabs((*sit).second->avgl[c] - avgl[c]);
}
}
sigPriorityQueue pqResults; /* results priority queue; largest at top */
sigIterator sit = dbSpace[dbId]->sigs.begin();
// Fill up the numres-bounded priority queue (largest at top):
for (int cnt = 0; cnt < numres; cnt++) {
if (sit == dbSpace[dbId]->sigs.end())
// No more images; cannot get requested numres, alas.
return V;
pqResults.push(*(*sit).second);
sit++;
}
for (; sit != dbSpace[dbId]->sigs.end(); sit++) {
if ((*sit).second->score < pqResults.top().score) {
// Make room by dropping largest entry:
pqResults.pop();
// Insert new entry:
pqResults.push(*(*sit).second);
}
}
SigStruct curResTmp; /* current result waiting to be returned */
while (pqResults.size()) {
curResTmp = pqResults.top();
pqResults.pop();
V.insert(V.end(), curResTmp.id);
V.insert(V.end(), curResTmp.score);
}
return V;
}
/* sig1,2,3 are int arrays of lenght NUM_COEFS
avgl is the average luminance
thresd is the limit similarity threshold. Only images with score > thresd will be a result
`sketch' tells which set of weights to use
sigs is the source to query on (map of signatures)
every search result is removed from sigs. (right now this functn is only used by clusterSim)
*/
long_list queryImgDataForThres(const int dbId, sigMap * tsigs,
Idx * sig1, Idx * sig2, Idx * sig3,
double *avgl, float thresd, int sketch) {
int idx, c;
int pn;
long_list res;
Idx *sig[3] = { sig1, sig2, sig3 };
if (!validate_dbid(dbId)) { cerr << "ERROR: database space not found (" << dbId << ")" << endl; return res;}
for (sigIterator sit = (*tsigs).begin(); sit != (*tsigs).end(); sit++) {
(*sit).second->score = 0;
for (c = 0; c < 3; c++)
(*sit).second->score += weights[sketch][0][c]
* fabs((*sit).second->avgl[c] - avgl[c]);
}
for (int b = 0; b < NUM_COEFS; b++) { // for every coef on a sig
for (c = 0; c < 3; c++) {
#ifdef FAST_POW_GEERT
pn = sig[c][b] < 0;
idx = (sig[c][b] - pn) ^ -pn;
#else
pn = 0;
if (sig[c][b]>0) {
pn = 0;
idx = sig[c][b];
} else {
pn = 1;
idx = -sig[c][b];
}
#endif
// update the score of every image which has this coef
long_listIterator end = dbSpace[dbId]->imgbuckets[c][pn][idx].end();
for (long_listIterator uit = dbSpace[dbId]->imgbuckets[c][pn][idx].begin();
uit != end; uit++) {
if ((*tsigs).count((*uit)))
// this is an ugly line
(*tsigs)[(*uit)]->score -=
weights[sketch][imgBin[idx]][c];
}
}
}
for (sigIterator sit = (*tsigs).begin(); sit != (*tsigs).end(); sit++) {
if ((*sit).second->score < thresd) {
res.push_back((*sit).second->id);
(*tsigs).erase((*sit).second->id);
}
}
return res;
}
long_list queryImgDataForThresFast(sigMap * tsigs, double *avgl, float thresd, int sketch) {
// will only look for average luminance
long_list res;
for (sigIterator sit = (*tsigs).begin(); sit != (*tsigs).end(); sit++) {
(*sit).second->score = 0;
for (int c = 0; c < 3; c++)
(*sit).second->score += weights[sketch][0][c]
* fabs((*sit).second->avgl[c] - avgl[c]);
if ((*sit).second->score < thresd) {
res.push_back((*sit).second->id);
(*tsigs).erase((*sit).second->id);
}
}
return res;
}
// cluster by similarity. Returns list of list of long ints (img ids)
/*
long_list_2 clusterSim(const int dbId, float thresd, int fast = 0) {
long_list_2 res; // will hold a list of lists. ie. a list of clusters
sigMap wSigs(dbSpace[dbId]->sigs); // temporary map of sigs, as soon as an image becomes part of a cluster, it's removed from this map
sigMap wSigsTrack(dbSpace[dbId]->sigs); // temporary map of sigs, as soon as an image becomes part of a cluster, it's removed from this map
for (sigIterator sit = wSigs.begin(); sit != wSigs.end(); sit++) { // for every img on db
long_list res2;
if (fast) {
res2 =
queryImgDataForThresFast(&wSigs, (*sit).second->avgl,
thresd, 1);
} else {
res2 =
queryImgDataForThres(dbId, &wSigs, (*sit).second->sig1,
(*sit).second->sig2,
(*sit).second->sig3,
(*sit).second->avgl, thresd, 1);
}
// continue;
long int hid = (*sit).second->id;
// if ()
wSigs.erase(hid);
if (res2.size() <= 1) {
if (wSigs.size() <= 1)
break; // everything already added to a cluster sim. Bail out immediately, otherwise next iteration
// will segfault when incrementing sit
continue;
}
res2.push_front(hid);
res.push_back(res2);
if (wSigs.size() <= 1)
break;
// sigIterator sit2 = wSigs.end();
// sigIterator sit3 = sit++;
}
return res;
}
*/
std::vector<double> queryImgID(const int dbId, long int id, int numres) {
/*query for images similar to the one that has this id
numres is the maximum number of results
*/
if (id == -1) { // query random images
vector<double> Vres;
if (!validate_dbid(dbId)) { cerr << "ERROR: database space not found (" << dbId << ")" << endl; return Vres;}
long int sz = dbSpace[dbId]->sigs.size();
int_hashset includedIds;
sigIterator it = dbSpace[dbId]->sigs.begin();
for (int var = 0; var < min(sz, numres); ) { // var goes from 0 to numres
long int rint = rand()%(sz);
for(int pqp =0; pqp < rint; pqp++) {
it ++;
if (it == dbSpace[dbId]->sigs.end()) {
it = dbSpace[dbId]->sigs.begin();
continue;
}
}
if ( includedIds.count((*it).first) == 0 ) { // havent added this random result yet
Vres.insert(Vres.end(), (*it).first );
Vres.insert(Vres.end(), 0 );
includedIds.insert((*it).first);
++var;
}
}
return Vres;
}
if (!validate_imgid(dbId, id)) { cerr << "ERROR: image id (" << id << ") not found on given dbid (" << dbId << ") or dbid not existant" << endl ; return std::vector<double>();};
return queryImgData(dbId, dbSpace[dbId]->sigs[id]->sig1, dbSpace[dbId]->sigs[id]->sig2, dbSpace[dbId]->sigs[id]->sig3,
dbSpace[dbId]->sigs[id]->avgl, numres, 0);
}
std::vector<double> queryImgFile(char* filename,const int dbId, int numres,int sketch = 0)
{
/*query for images similar to the one on filename
numres is the maximum number of results
sketch should be 1 if this image is a drawing
*/
double avgl[3];
Idx sig1[NUM_COEFS];
Idx sig2[NUM_COEFS];
Idx sig3[NUM_COEFS];
int cn = 0;
static Unit cdata1[16384];
static Unit cdata2[16384];
static Unit cdata3[16384];
int width, height;
ExceptionInfo exception;
GetExceptionInfo(&exception);
ImageInfo *image_info;
image_info = CloneImageInfo((ImageInfo *) NULL);
(void) strcpy(image_info->filename, filename);
Image *image = ReadImage(image_info, &exception);
if (exception.severity != UndefinedException) CatchException(&exception);
DestroyImageInfo(image_info);
DestroyExceptionInfo(&exception);
if (image == (Image *) NULL) {
cerr << "ERROR: unable to read image" << endl;
std::vector<double> vect;
return vect;
}
Image *resize_image;
/*
Initialize the image info structure and read an image.
*/
GetExceptionInfo(&exception);
width = image->columns;
height = image->rows;
resize_image = SampleImage(image, 128, 128, &exception);
DestroyImage(image);
DestroyExceptionInfo(&exception);
unsigned char rchan[16384];
unsigned char gchan[16384];
unsigned char bchan[16384];
GetExceptionInfo(&exception);
const PixelPacket *pixel_cache = AcquireImagePixels(resize_image, 0, 0, 128, 128, &exception);
for (int idx = 0; idx < 16384; idx++) {
rchan[idx] = pixel_cache->red;
gchan[idx] = pixel_cache->green;
bchan[idx] = pixel_cache->blue;
pixel_cache++;
}