-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimage.c
1735 lines (1428 loc) · 53.5 KB
/
image.c
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
/* Departamento de Informatica, PUC-Rio, INF1761 Computer Graphhics
*
* @file cor.h TAD: digital image (implementation).
* @author Marcelo Gattass and others
*
* @date
* Last versio: 08/2011.
*
* @version 3.1
*
* @Copyright/License
* DI PUC-Rio Educational Software
* All the products under this license are free software: they can be used for both academic and commercial purposes at absolutely no cost.
* There are no paperwork, no royalties, no GNU-like "copyleft" restrictions, either. Just download and use it.
* They are licensed under the terms of the MIT license reproduced below, and so are compatible with GPL and also qualifies as Open Source software.
* They are not in the public domain, PUC-Rio keeps their copyright. The legal details are below.
*
* The spirit of this license is that you are free to use the libraries for any purpose at no cost without having to ask us.
* The only requirement is that if you do use them, then you should give us credit by including the copyright notice below somewhere in your product or its documentation.
*
* Copyright © 2010-2011 DI PUC-Rio Educational Software
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software
* without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sub license, and/or sell copies of the Software, and to permit
* persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or suavlantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*/
#define _CRT_SECURE_NO_WARNINGS
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include <math.h>
#include <float.h>
#include <memory.h>
#include "image.h"
#define ROUND(_) (int)floor( (_) + 0.5 )
#define N_CORES 256
#define MAIOR_COR 255
struct Image_imp {
int dcs; /* define a dim do espaco de cor (dimension of the color space): 3=RGB, 1=luminancia */
int width; /* numero de pixels na direcao horizontal da imagem */
int height; /* numero de pixels na direcao vertical da imagem */
float *buf; /* vetor de dimensao dcs*width*height que armazena consecutivamente as componentes de cor */
/* de cada pixel a partir do canto inferior esquerdo da imagem. */
/* A posicao das componentes de cor do pixel (x,y) fica armazenada */
/* a partir da posicao: (y*width*dcs) + (x*dcs) */
};
/************************************************************************/
/* Definicao das Funcoes Privadas */
/************************************************************************/
/* getuint e putuint:
* Funcoes auxiliares para ler e escrever inteiros na ordem (lo-hi)
* Note que no Windows as variaveis tipo "unsigned short int" sao
* armazenadas no disco em dois bytes na ordem inversa. Ou seja, o
* numero 400, por exemplo, que pode ser escrito como 0x190, fica
* armazenado em dois bytes consecutivos 0x90 e 0x01. Nos sistemas
* UNIX e Mac este mesmo inteiro seria armazenado na ordem 0x01 e
* 0x90. O armazenamento do Windows e' chamado de "little endian"
* (i.e., lowest-order byte stored first), e no sitemas Unix sao
* "big-endian" (i.e., highest-order byte stored first).
*/
/***************************************************************************
* Reads an unsigned integer from input *
***************************************************************************/
static int getuint(unsigned short *uint, FILE *input)
{
int got;
unsigned char temp[2];
unsigned short tempuint;
got = (int) fread(&temp, 1, 2, input);
if (got != 2) return 0;
tempuint = ((unsigned short)(temp[1])<<8) | ((unsigned short)(temp[0]));
*uint = tempuint;
return 1;
}
/***************************************************************************
* Writes an unsigned integer in output *
***************************************************************************/
static int putuint(unsigned short uint, FILE *output)
{
int put;
unsigned char temp[2];
temp[0] = uint & 0xff;
temp[1] = (uint >> 8) & 0xff;
put = (int) fwrite(&temp, 1, 2, output);
if (put != 2) return 0;
return 1;
}
/***************************************************************************
* Reads a long integer from input *
***************************************************************************/
static int getlong(FILE *input, long int *longint)
{
int got;
unsigned char temp[4];
long int templongint;
got = (int)fread(&temp, 1, 4, input);
if (got != 4) return 0;
templongint = ((long int)(temp[3])<<24) | ((long int)(temp[2])<<16)
| ((long int)(temp[1])<<8) | ((long int)(temp[0]));
*longint = templongint;
return 1;
}
/***************************************************************************
* Writes a long integer in output *
***************************************************************************/
static int putlong(FILE *output, long int longint)
{
int put;
unsigned char temp[4];
temp[0] = (unsigned char)longint & 0xff;
temp[1] = (unsigned char)(longint >> 8) & 0xff;
temp[2] = (unsigned char)(longint >> 16) & 0xff;
temp[3] = (unsigned char)(longint >> 24) & 0xff;
put = (int)fwrite(&temp, 1, 4, output);
if (put != 4) return 0;
return 1;
}
/***************************************************************************
* Reads a word from input *
***************************************************************************/
static int getword(FILE *input, unsigned short int *word)
{
int got;
unsigned char temp[2];
unsigned short int tempword;
got = (int)fread(&temp, 1, 2, input);
if (got != 2) return 0;
tempword = ((unsigned short int)(temp[1])<<8) | ((unsigned short int)(temp[0]));
*word = tempword;
return 1;
}
/***************************************************************************
* Writes a word in output *
***************************************************************************/
static int putword(FILE *output, unsigned short int word)
{
int put;
unsigned char temp[2];
temp[0] = word & 0xff;
temp[1] = (word >> 8) & 0xff;
put = (int)fwrite(&temp, 1, 2, output);
if (put != 2) return 0;
return 1;
}
/***************************************************************************
* Reads a double word from input *
***************************************************************************/
static int getdword(FILE *input, unsigned long int *dword)
{
int got;
unsigned char temp[4];
unsigned long int tempdword;
got = (int)fread(&temp, 1, 4, input);
if (got != 4) return 0;
tempdword = ((unsigned long int)(temp[3])<<24) | ((unsigned long int)(temp[2])<<16)
| ((unsigned long int)(temp[1])<<8) | ((unsigned long int)(temp[0]));
*dword = tempdword;
return 1;
}
/***************************************************************************
* Writes a double word in output *
***************************************************************************/
static int putdword(FILE *output, unsigned long int dword)
{
int put;
unsigned char temp[4];
temp[0] = (unsigned char) (dword & 0xff);
temp[1] = (unsigned char) ((dword >> 8) & 0xff);
temp[2] = (unsigned char) ((dword >> 16) & 0xff);
temp[3] = (unsigned char) ((dword >> 24) & 0xff);
put = (int)fwrite(&temp, 1, 4, output);
if (put != 4) return 0;
return 1;
}
static float luminance(float red, float green, float blue)
{
return 0.2126f*red +0.7152f*green+0.0722f*blue;
}
/************************************************************************/
/* Definicao das Funcoes Exportadas */
/************************************************************************/
Image* imgCreate(int w, int h, int dcs)
{
Image* image = (Image*) malloc (sizeof(Image));
assert(image);
image->width = w;
image->height = h;
image->dcs = dcs;
image->buf = calloc (w * h * dcs , sizeof(float));
assert(image->buf);
return image;
}
void imgDestroy(Image* image)
{
if (image)
{
if (image->buf) free (image->buf);
free(image);
}
}
Image* imgCopy(Image* image)
{
int w = imgGetWidth(image);
int h = imgGetHeight(image);
int dcs = imgGetDimColorSpace(image);
Image* img1=imgCreate(w,h,dcs);
int x,y;
float rgb[3];
for (y=0;y<h;y++){
for (x=0;x<w;x++) {
imgGetPixel3fv(image,x,y,rgb);
imgSetPixel3fv(img1,x,y,rgb);
}
}
return img1;
}
Image* imgGrey(Image* image)
{
int w = imgGetWidth(image);
int h = imgGetHeight(image);
Image* img1=imgCreate(w,h,1);
int x,y;
float rgb[3],grey[3];
for (y=0;y<h;y++){
for (x=0;x<w;x++) {
imgGetPixel3fv(image,x,y,rgb);
grey[0]=luminance(rgb[0],rgb[1],rgb[2]);
grey[1]=grey[0];
grey[2]=grey[0];
imgSetPixel3fv(img1,x,y,grey);
}
}
return img1;
}
Image* imgResize(Image* img0, int w1, int h1)
{
Image* img1 = imgCreate(w1,h1,img0->dcs);
float w0 = (float) img0->width; /* passa para float para fazer contas */
float h0 = (float) img0->height;
int x0,y0,x1,y1;
float color[3];
for (y1=0;y1<h1;y1++)
for (x1=0;x1<w1;x1++)
{
x0=ROUND(w0*x1/w1); /* pega a cor do pixel mais proxima */
y0=ROUND(h0*y1/h1);
imgGetPixel3fv(img0,x0,y0,color);
imgGetPixel3fv(img1,x1,y1,color);
}
return img1;
}
Image* imgAdjust2eN(Image*img0)
{
Image* img1;
int i=0,valid[14]={1,2,4,8,16,32,64,128,512,1024,2048,4096,8192,16384};
int w0=img0->width;
int h0=img0->height;
int w1,h1;
int x,y;
float rgb[3],black[3]={0.f,0.f,0.f};
for (i=0;i<14&&valid[i]<w0;i++);
w1=valid[i];
for (i=0;i<14&&valid[i]<h0;i++);
h1=valid[i];
img1=imgCreate(w1,h1, img0->dcs);
for (y=0;y<h1;y++){
for (x=0;x<w1;x++) {
if (x<w0&&y<h0) {
imgGetPixel3fv(img0,x,y,rgb);
imgSetPixel3fv(img1,x,y,rgb);
}
else
imgSetPixel3fv(img1,x,y,black);
}
}
return img1;
}
float imgDif(Image*img0, Image*img1, float gamma)
{
int w = imgGetWidth(img0);
int h = imgGetHeight(img0);
int x,y;
float rgb[3],rgb0[3],rgb1[3],avg=0.f,tot=0.f;
for (y=0;y<h;y++){
for (x=0;x<w;x++) {
float lum,new_lum,ratio;
imgGetPixel3fv(img0,x,y,rgb0);
imgGetPixel3fv(img1,x,y,rgb1);
/* calcula o modulo da diferenca */
rgb[0]=(rgb1[0]>rgb0[0])? rgb1[0]-rgb0[0] : rgb0[0]-rgb1[0] ;
rgb[1]=(rgb1[1]>rgb0[1])? rgb1[1]-rgb0[1] : rgb0[1]-rgb1[1] ;
rgb[2]=(rgb1[2]>rgb0[2])? rgb1[2]-rgb0[2] : rgb0[2]-rgb1[2] ;
/* acumula a soma */
avg+=(rgb[0]+rgb[1]+rgb[2]);
tot+=(rgb0[0]+rgb0[1]+rgb0[2]);
/* corrige por gamma */
lum = luminance(rgb[0],rgb[1],rgb[2]);
new_lum = (float) pow(lum,1./gamma);
ratio = new_lum/lum;
rgb[0]*=ratio; rgb[1]*=ratio; rgb[2]*=ratio;
imgSetPixel3fv(img0,x,y,rgb);
}
}
avg=100*avg/tot;
return avg;
}
float imgErr(Image*img0, Image*img1)
{
int w = imgGetWidth(img0);
int h = imgGetHeight(img0);
int x,y;
float rgb0[3],rgb1[3],delta_rgb[3],avg=0.f,tot=0.f;
for (y=0;y<h;y++){
for (x=0;x<w;x++) {
imgGetPixel3fv(img0,x,y,rgb0);
imgGetPixel3fv(img1,x,y,rgb1);
/* calcula o modulo da diferenca */
delta_rgb[0]=(rgb1[0]>rgb0[0])? rgb1[0]-rgb0[0] : rgb0[0]-rgb1[0] ;
delta_rgb[1]=(rgb1[1]>rgb0[1])? rgb1[1]-rgb0[1] : rgb0[1]-rgb1[1] ;
delta_rgb[2]=(rgb1[2]>rgb0[2])? rgb1[2]-rgb0[2] : rgb0[2]-rgb1[2] ;
/* acumula a soma */
avg+=(delta_rgb[0]+delta_rgb[1]+delta_rgb[2]);
tot+=(rgb0[0]+rgb0[1]+rgb0[2]);
}
}
avg=avg/tot;
return 100*avg;
}
int imgGetWidth(Image* image)
{
return image->width;
}
int imgGetHeight(Image* image)
{
return image->height;
}
int imgGetDimColorSpace(Image* image)
{
return image->dcs;
}
float* imgGetData(Image* image)
{
return image->buf;
}
void imgSetPixel3fv(Image* image, int x, int y, float* color)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
switch (image->dcs) {
case 3:
image->buf[pos ] = color[0];
image->buf[pos+1] = color[1];
image->buf[pos+2] = color[2];
break;
case 1:
image->buf[pos ] = luminance(color[0],color[1],color[2]);
break;
default:
break;
}
}
void imgSetPixel3f(Image* image, int x, int y, float R, float G, float B)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
switch (image->dcs) {
case 3:
image->buf[pos ] = R;
image->buf[pos+1] = G;
image->buf[pos+2] = B;
break;
case 1:
image->buf[pos ] = luminance(R,G,B);
break;
default:
break;
}
}
void imgGetPixel3fv(Image* image, int x, int y, float* color)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
switch (image->dcs) {
case 3:
color[0] = image->buf[pos ];
color[1] = image->buf[pos+1];
color[2] = image->buf[pos+2];
break;
case 1:
color[0] = image->buf[pos ];
color[1] = color[0];
color[2] = color[0];
break;
default:
break;
}
}
void imgGetPixel3f(Image* image, int x, int y, float* R, float* G, float* B)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
switch (image->dcs) {
case 3:
*R = image->buf[pos ];
*G = image->buf[pos+1];
*B = image->buf[pos+2];
break;
case 1:
*R = image->buf[pos ];
*G = *R;
*B = *R;
break;
default:
break;
}
}
void imgSetPixel3ubv(Image* image, int x, int y, unsigned char * color)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
switch (image->dcs) {
case 3:
image->buf[pos ] = (float)(color[0]/255.);
image->buf[pos+1] = (float)(color[1]/255.);
image->buf[pos+2] = (float)(color[2]/255.);
break;
case 1:
image->buf[pos ] = luminance((float)(color[0]/255.),(float)(color[1]/255.),(float)(color[2]/255.));
break;
default:
break;
}
}
void imgGetPixel3ubv(Image* image, int x, int y, unsigned char *color)
{
int pos = (y*image->width*image->dcs) + (x*image->dcs);
int r,g,b;
switch (image->dcs) {
case 3:
r= ROUND(255*image->buf[pos]);
g= ROUND (255*image->buf[pos+1]);
b= ROUND (255*image->buf[pos+2]);
color[0] = (unsigned char)(r<256) ? r : 255 ;
color[1] = (unsigned char)(g<256) ? g : 255 ;
color[2] = (unsigned char)(b<256) ? b : 255 ;
break;
case 1:
r=g=b= ROUND(255*image->buf[pos]);
color[0] = (unsigned char)(r<256) ? r : 255 ;
color[1] = (unsigned char)(g<256) ? g : 255 ;
color[2] = (unsigned char)(b<256) ? b : 255 ;
break;
default:
break;
}
}
Image* imgReadTGA(char *filename)
{
FILE *filePtr;
Image *image; /* imagem a ser criada */
unsigned char *buffer; /* buffer para ler o vetor de rgb da imagem */
unsigned char imageType; /* 2 para imagens RGB */
unsigned short int imageWidth; /* largura da imagem */
unsigned short int imageHeight; /* altura da imagem */
unsigned char bitCount; /* numero de bits por pixel */
int x,y; /* posicao de um pixel */
unsigned char ucharSkip; /* dado lixo unsigned char */
short int sintSkip; /* dado lixo short int */
/* abre o arquivo com a imagem TGA */
filePtr = fopen(filename, "rb");
assert(filePtr);
/* pula os primeiros dois bytes que devem ter valor zero */
ucharSkip = getc(filePtr); /* tamanho do descritor da imagem (0) */
if (ucharSkip != 0) printf("erro na leitura de %s: imagem com descritor\n", filename);
ucharSkip = getc(filePtr);
if (ucharSkip != 0) printf("erro na leitura de %s: imagem com tabela de cores\n", filename);
/* le o tipo de imagem (que deve ser obrigatoriamente 2).
nao estamos tratando dos outros tipos */
imageType=getc(filePtr);
assert(imageType == 2);
/* pula 9 bytes relacionados com a tabela de cores
(que nao existe quando a imagem e' RGB, imageType=2) */
getuint((short unsigned int *)&sintSkip,filePtr);
getuint((short unsigned int *)&sintSkip,filePtr);
ucharSkip = getc(filePtr);
/* especificacao da imagem */
getuint((short unsigned int *)&sintSkip,filePtr); /* origem em x (por default = 0) */
getuint((short unsigned int *)&sintSkip,filePtr); /* origem em y (por default = 0) */
getuint(&imageWidth,filePtr); /* largura */
getuint(&imageHeight,filePtr); /* altura */
/* read image bit depth */
bitCount=getc(filePtr);
assert(bitCount == 24); /* colorMode -> 3 = BGR (24 bits) */
/* read 1 byte of garbage data */
ucharSkip = getc(filePtr);
/* cria uma instancia do tipo Imagem */
image = imgCreate(imageWidth,imageHeight,3);
buffer = (unsigned char *) malloc(3*imageWidth*imageHeight*sizeof(unsigned char));
assert(image);
assert(buffer);
/* read in image data */
fread(buffer, sizeof(unsigned char), 3*imageWidth*imageHeight, filePtr);
/* copia e troca as compontes de BGR para RGB */
for (y=0;y<imageHeight;y++) {
for (x=0;x<imageWidth;x++) {
unsigned char color[3];
int pos = (y*imageWidth*3) + (x*3);
color[0] = buffer[pos+2];
color[1] = buffer[pos+1];
color[2] = buffer[pos ];
imgSetPixel3ubv(image,x,y,color);
}
}
free(buffer);
fclose(filePtr);
return image;
}
int imgWriteTGA(char *filename, Image* image)
{
unsigned char imageType=2; /* RGB(A) sem compressão */
unsigned char bitDepth=24; /* 24 bits por pixel */
FILE *filePtr; /* ponteiro do arquivo */
unsigned char * buffer; /* buffer de bytes */
int x,y;
unsigned char byteZero=0; /* usado para escrever um byte zero no arquivo */
short int shortZero=0; /* usado para escrever um short int zero no arquivo */
if (!image) return 0;
/* cria um arquivo binario novo */
filePtr = fopen(filename, "wb");
assert(filePtr);
/* cria o buffer */
buffer = (unsigned char *) malloc(3*image->width*image->height*sizeof(unsigned char));
assert(buffer);
/* copia e troca as compontes de BGR para RGB */
for (y=0;y<image->height;y++) {
for (x=0;x<image->width;x++) {
unsigned char color[3];
int pos = (y*image->width*3) + (x*3);
imgGetPixel3ubv(image,x,y,color);
buffer[pos+2] = color[0];
buffer[pos+1] = color[1];
buffer[pos ] = color[2];
}
}
/* escreve o cabecalho */
putc(byteZero,filePtr); /* 0, no. de caracteres no campo de id da imagem */
putc(byteZero,filePtr); /* = 0, imagem nao tem palheta de cores */
putc(imageType,filePtr); /* = 2 -> imagem "true color" (RGB) */
putuint(shortZero,filePtr); /* info sobre a tabela de cores (inexistente) */
putuint(shortZero,filePtr); /* idem */
putc(byteZero,filePtr); /* idem */
putuint(shortZero,filePtr); /* =0 origem em x */
putuint(shortZero,filePtr); /* =0 origem em y */
putuint(image->width,filePtr); /* largura da imagem em pixels */
putuint(image->height,filePtr); /* altura da imagem em pixels */
putc(bitDepth,filePtr); /* numero de bits de um pixel */
putc(byteZero, filePtr); /* =0 origem no canto inf esquedo sem entrelacamento */
/* escreve o buf de cores da imagem */
fwrite(buffer, sizeof(unsigned char), 3*image->width*image->height, filePtr);
free(buffer);
fclose(filePtr);
return 1;
}
/* Compiler dependent definitions */
typedef unsigned char BYTE;
typedef unsigned short int USHORT;
typedef unsigned short int WORD;
typedef long int LONG;
typedef unsigned long int DWORD;
Image* imgReadBMP(char *filename)
{
FILE *filePtr; /* ponteiro do arquivo */
Image*image; /* imagem a ser criada */
BYTE *linedata;
USHORT bfType; /* "BM" = 19788 */
LONG biWidth; /* image width in pixels */
LONG biHeight; /* image height in pixels */
WORD biBitCount; /* bitmap color depth */
DWORD bfSize;
USHORT ushortSkip; /* dado lixo USHORT */
DWORD dwordSkip; /* dado lixo DWORD */
LONG longSkip; /* dado lixo LONG */
WORD wordSkip; /* dado lixo WORD */
LONG i, j, k, l, linesize, got;
/* abre o arquivo com a imagem BMP */
filePtr = fopen(filename, "rb");
assert(filePtr);
/* verifica se eh uma imagem bmp */
getuint(&bfType, filePtr);
assert(bfType == 19778);
/* pula os 12 bytes correspondentes a bfSize, Reserved1 e Reserved2 */
getdword(filePtr, &bfSize);
getuint(&ushortSkip, filePtr); /* Reserved1, deve ter valor 0 */
assert(ushortSkip == 0);
getuint(&ushortSkip, filePtr); /* Reserved2, deve ter valor 0 */
assert(ushortSkip == 0);
/* pula os 4 bytes correspondentes a bfOffBits, que deve ter valor 54 */
getdword(filePtr, &dwordSkip);
assert(dwordSkip == 54);
/* pula os 4 bytes correspondentes a biSize, que deve ter valor 40 */
getdword(filePtr, &dwordSkip);
assert(dwordSkip == 40);
/* pega largura e altura da imagem */
getlong(filePtr, &biWidth);
getlong(filePtr, &biHeight);
/* verifica que o numero de quadros eh igual a 1 */
getword(filePtr, &wordSkip);
assert(wordSkip == 1);
/* Verifica se a imagem eh de 24 bits */
getword(filePtr, &biBitCount);
if(biBitCount != 24)
{
fprintf(stderr, "imgReadBMP: Not a bitmap 24 bits file.\n");
fclose(filePtr);
return (NULL);
}
/* pula os demais bytes do infoheader */
getdword(filePtr, &dwordSkip);
assert(dwordSkip == 0);
getdword(filePtr, &dwordSkip);
getlong(filePtr, &longSkip);
getlong(filePtr, &longSkip);
getdword(filePtr, &dwordSkip);
getdword(filePtr, &dwordSkip);
image = imgCreate(biWidth, biHeight,3);
/* a linha deve terminar em uma fronteira de dword */
linesize = 3*image->width;
if (linesize & 3) {
linesize |= 3;
linesize++;
}
/* aloca espaco para a area de trabalho */
linedata = (BYTE *) malloc(linesize);
if (linedata == NULL) {
fprintf(stderr, "get24bits: Not enough memory.\n");
return 0;
}
/* pega as componentes de cada pixel */
for (k=0, i=0; i<image->height; i++) {
got = (unsigned long int)fread(linedata, linesize, 1, filePtr);
if (got != 1) {
free(linedata);
fprintf(stderr, "get24bits: Unexpected end of file.\n");
}
for (l=1, j=0; j<image->width; j++, l=l+3) {
image->buf[k++] = (float)(linedata[l+1]/255.);
image->buf[k++] = (float)(linedata[l ]/255.);
image->buf[k++] = (float)(linedata[l-1]/255.);
}
}
free(linedata);
fclose(filePtr);
return image;
}
int imgWriteBMP(char *filename, Image* bmp)
{
FILE *filePtr; /* ponteiro do arquivo */
unsigned char *filedata;
DWORD bfSize;
int i, k, l;
int linesize, put;
if (!bmp) return 0;
/* cria um novo arquivo binario */
filePtr = fopen(filename, "wb");
assert(filePtr);
/* a linha deve terminar em uma double word boundary */
linesize = bmp->width * 3;
if (linesize & 3) {
linesize |= 3;
linesize ++;
}
/* calcula o tamanho do arquivo em bytes */
bfSize = 14 + /* file header size */
40 + /* info header size */
bmp->height * linesize; /* image data size */
/* Preenche o cabeçalho -> FileHeader e InfoHeader */
putuint(19778, filePtr); /* type = "BM" = 19788 */
putdword(filePtr, bfSize); /* bfSize -> file size in bytes */
putuint(0, filePtr); /* bfReserved1, must be zero */
putuint(0, filePtr); /* bfReserved2, must be zero */
putdword(filePtr, 54); /* bfOffBits -> offset in bits to data */
putdword(filePtr, 40); /* biSize -> structure size in bytes */
putlong(filePtr, bmp->width); /* biWidth -> image width in pixels */
putlong(filePtr, bmp->height); /* biHeight -> image height in pixels */
putword(filePtr, 1); /* biPlanes, must be 1 */
putword(filePtr, 24); /* biBitCount, 24 para 24 bits -> bitmap color depth */
putdword(filePtr, 0); /* biCompression, compression type -> no compression */
putdword(filePtr, 0); /* biSizeImage, nao eh usado sem compressao */
putlong(filePtr, 0); /* biXPelsPerMeter */
putlong(filePtr, 0); /* biYPelsPerMeter */
putdword(filePtr, 0); /* biClrUsed, numero de cores na palheta */
putdword(filePtr, 0); /* biClrImportant, 0 pq todas sao importantes */
/* aloca espacco para a area de trabalho */
filedata = (unsigned char *) malloc(linesize);
assert(filedata);
/* a linha deve ser zero padded */
for (i=0; i<(linesize-(3*bmp->width)); i++)
filedata[linesize-1-i] = 0;
for (k=0; k<bmp->height;k++)
{
l = 1;
/* coloca as componentes BGR no buffer */
for (i=0; i<bmp->width; i++) {
unsigned char color[3];
int r,g,b;
imgGetPixel3ubv(bmp,i,k,color);
r= color[0];
g= color[1];
b= color[2];
filedata[l-1] = (unsigned char)(b<256) ? b : 255 ;
filedata[l ] = (unsigned char)(g<256) ? g : 255 ;
filedata[l+1] = (unsigned char)(r<256) ? r : 255 ;
l+=3;
}
/* joga para o arquivo */
put = (int)fwrite(filedata, linesize, 1, filePtr);
if (put != 1) {
fprintf(stderr, "put24bits: Disk full.");
free(filedata);
return 0;
}
}
/* operacao executada com sucesso */
fprintf(stdout,"imgWriteBMP: %s successfuly generated\n",filename);
free(filedata);
fclose(filePtr);
return 1;
}
/*- PFM Interface Functions ---------------------------------------*/
Image* imgReadPFM(char *filename)
{
FILE *fp;
Image* img;
float scale;
int w,h;
char line[256];
fp = fopen(filename, "rb");
if (fp == NULL) { printf("%s nao pode ser aberto\n",filename); return NULL;}
fgets(line,256,fp);
if(strcmp(line,"PF\n"))
{
return 0;
}
while (fscanf( fp, " %d ", &w ) != 1)
fgets(line, 256, fp);
while (fscanf( fp, " %d ", &h ) != 1)
fgets(line, 256, fp);
while (fscanf( fp, " %f", &scale ) != 1)
fgets(line, 256, fp);
fgetc(fp);
img = imgCreate(w,h,3);
fread( img->buf, 3*w*h, sizeof(float), fp );
fprintf(stdout,"imgReadPFM: %s successfuly loaded\n",filename);
fclose(fp);
return img;
}
int imgWritePFM(char * filename, Image* img)
{
FILE * fp;
float scale=1.f;
if ((fp = fopen(filename, "wb")) == NULL) {
printf("\nNão foi possivel abrir o arquivo %s\n",filename);
return 0;
}
/* the ppm file header */
fprintf(fp,"PF\n%d %d\n%f\n", img->width, img->height, scale);
fwrite( img->buf, 3*img->width*img->height, sizeof(float), fp );
fprintf(stdout,"imgWritePFM: %s successfuly created\n",filename);
fclose(fp);
return 1;
}
static int comparaCor3(const void * p1, const void * p2)
{
int *c1 = (int *) p1; /* aponta para o vermelho quantizado da cor 1 */
int *c2 = (int *) p2; /* aponta para o vermelho quantizado da cor 2 */
/* compara o canal vermelho */
if (*c1 < *c2) return -1;
if (*c1 > *c2) return 1;
/* compara o canal verde, uma vez que o vermelho e' igual */
c1++; c2++;
if (*c1 < *c2) return -1;
if (*c1 > *c2) return 1;
/* compara o canal azul, uma vez que o vermelho e o azul sao iguais */
c1++; c2++;
if (*c1 < *c2) return -1;
if (*c1 > *c2) return 1;
/* sao iguais */
return 0;
}
static int comparaCor1(const void * p1, const void * p2)
{
int *c1 = (int *) p1; /* aponta para a luminosidade quantizada da cor 1 */
int *c2 = (int *) p2; /* aponta para a luminosidade quantizada da cor 2 */
/* compara o canal de luminosidade */
if (*c1 < *c2) return -1;
if (*c1 > *c2) return 1;
/* sao iguais */
return 0;
}
int imgCountColor(Image * img, float tol)
{
int numCor = 1;
int w = imgGetWidth(img);
int h = imgGetHeight(img);
int dcs = imgGetDimColorSpace(img);
float* buf=imgGetData(img);
int *vet=(int*) malloc(3*w*h*sizeof(int));
int i;
/* copia o buffer da imagem no vetor de floats fazendo
uma quantizacao para (1/tol) tons de cada componente de cor */
for (i=0;i<dcs*w*h;i++)
vet[i] = (int)(buf[i]/tol+0.5);
/* ordena o vetor */
if (dcs==3)
qsort(vet,w*h,3*sizeof(int),comparaCor3);
else
qsort(vet,w*h,sizeof(int),comparaCor1);