Imagem Digital
1. Modelo matemático
2. Amostragem, quantização e codificação
3. Processamentos de imagens
4. Transformações e composição
Marcelo Gattas – DI / PUC-Rio
MGattass 0 50 100 150 200 250 0 100 200 300 400 500 600
Imagem: uma função do R
2em C
u v L L(u,v) Histograma Função (a) (b)
MGattass
Imagem Colorida
MGattassCanais de cor
canal v ermelh o canal verde can al a zulMGattass
Imagem colorida
R G B u vAquisição de imagens digitais
MGattass
Amostragem, quantização
e codificação de f(x)
partição do eixo x x função original f(x) amostra 0 1 2 3 4 5 6 MGattass codificação = (3, 4, 5, 5, 4, 2, 2, 3, 5, 5, 4, 2)Amostragem, quantização
e codificação de f(x)
0 1 2 3 4 5 6 x função original amostra quantizada f(x) × × × × × × × × × × × × × partição do eixo xMGattass
Digitalização de Imagens
Discretização espacial (amostragem)
MGattass
Digitalização de Imagens
amostragem
Imagem de tons contínuos 55 55 55 55 55 55 55 55 20 22 23 45 55 55 55 55 10 09 11 55 55 55 55 43 42 70 55 55 55 55 28 76 22 55 55 55 55 55 55 555555 64x54 64x54 - 16 corescodificação
Imagem amostrada Imagem amostrada e quantizada 5*55, 1*55, 1*20, 1*22, ….quantização
Imagem amostrada, quantizada e codificadaMGattass
Propriedades
MGattass
(a) aumento de resolução
Re-amostragem de f(x)
x f(x) × × × × × × × × × × × × × 0 1 2 3 4 5 6MGattass
(a) aumento de resolução
Re-amostragem de f(x)
x f(x) × × × × × × × × × × × × × função reconstruída pelo vizinho mais próximo função reconstruída por interpolação linear função original 0 1 2 3 4 5 6 MGattassRe-amostragem de f(x)
x f(x) × × × × × × × × × × × × × função reconstruída pelo vizinho mais próximofunção reconstruída por interpolação linear
função original
(a) redução de resolução
0 1 2 3 4 5 6
MGattass
Teorema de Nyquist
x f(x) x f(x) MGattassResolução espacial
10 x 8 14 x 10 8 x 5 valores interpolados valores médiosMGattass
Mudanças na r
esolução
espacial
312×194 156×97 78×48 312×194 312×192 78×49 156×97 312×194 312×194bicúbica
mais
próximo
Irreversível MGattassMGattass
Quantização de 24 para 8 bits
MGattass
MGattass
Codificação
MGattass
Memória gráfica indexada
0 0 0 B G R Tabela de cores Memória gráfica
MGattass
Codificação uniforme
30000 TOTAL 600 3 111 200 1 900 3 110 300 6/7 1800 3 101 600 5/7 2400 3 100 800 4/7 4800 3 011 1600 3/7 6300 3 010 2100 2/7 7500 3 001 2500 1/7 5700 3 000 1900 0 # bits tam. código # pixels tons Uniforme Podemos melhorar? MGattassConstrução da Árvore
Huffman
200 1 300 6/7 600 5/7 800 4/7 1600 3/7 1900 0 2100 2/7 2500 1/7 500 n0 600 5/7 800 4/7 1600 3/7 1900 0 2100 2/7 2500 1/7 n0 6/7 1MGattass
Construção da Árvore
Huffman
500 n0 600 5/7 800 4/7 1600 3/7 1900 0 2100 2/7 2500 1/7 n0 6/7 1 800 4/7 1100 n1 1600 3/7 1900 0 2100 2/7 2500 1/7 5/7 n1 MGattassConstrução da Árvore
Huffman
800 4/7 1100 n1 1600 3/7 1900 0 2100 2/7 2500 1/7 1600 3/7 1900 n2 1900 0 2100 2/7 2500 1/7 n0 6/7 1 5/7 n1 4/7 n2MGattass
Construção da Árvore
Huffman
1600 3/7 1900 n2 1900 0 2100 2/7 2500 1/7 n3 3500 1900 0 2100 2/7 2500 1/7 n0 6/7 1 5/7 n1 4/7 n2 3/7 n3 MGattassConstrução da Árvore
Huffman
n0 6/7 1 5/7 n1 4/7 n2 3500 n3 1900 0 2100 2/7 2500 1/7 3/7 n3 4000 n4 3500 n3 2500 1/7 n4 2/7 0MGattass
Construção da Árvore
Huffman
n0 6/7 1 5/7 n1 4/7 n2 3/7 n3 6000 n5 4000 n4 n4 2/7 0 4000 n4 3500 n3 2500 1/7 n5 1/7 n6 MGattassConstrução da Árvore
Huffman
1 0 11 10 01 00 111 110 1111 1110 1111 1 11 110 1111 01 111100 00 01 10 110 1110 11111 111100 111101 n0 n1 n2 n3 n4 n5 n6 6/7 1 5/7 4/7 3/7 0 2/7 1/7MGattass
Codificação de Huffman
27000 TOTAL 30000 TOTAL 1200 6 111100 600 3 111 200 1 1800 6 111101 900 3 110 300 6/7 3000 5 11111 1800 3 101 600 5/7 3200 4 1110 2400 3 100 800 4/7 4800 3 110 4800 3 011 1600 3/7 4200 2 01 6300 3 010 2100 2/7 5000 2 10 7500 3 001 2500 1/7 3800 2 00 5700 3 000 1900 0 # bits tam. código # bits tam. código # pixels tons Huffman UniformeProcessamentos no espaço
das cores
MGattass
Correção gama
MGattassCorreção gama
γ
L
L
←
MGattass
Tons de cinza e negativo
Lx,y= 0.299Rx,y + 0.587Gx,y+ 0.114Bx,ytons de cinza
Lx,y = 255 - Lx,y
Filtros espaciais
MGattass
Suavização
f h4
2
1 1 + −+
+
=
i i i if
f
f
h
MGattassMascara ou Filtro
4
2
1 1 + −+
+
=
i i i if
f
f
h
∑
− = −=
1 0 ) ( n k i i k ig
f
h
⎪
⎪
⎪
⎩
⎪⎪
⎪
⎨
⎧
+
>
+
=
=
−
=
−
<
=
1
0
1
4
/
1
0
4
/
2
1
4
/
1
1
0
l
se
l
se
l
se
l
se
l
se
g
l ou:MGattass
Convolução
∫
∞ = −∞ =−
=
t tdt
x
f
x
t
g
x
h
(
)
(
)
(
)
∑
− = −=
1 0 ) ( n k i i k ig
f
h
MGattassGaussiana
0.1 0.2 0.3 -4 -3 -2 -1 0 1 2 3 4 2 2 22
1
)
(
σσ
π
xe
x
G
−=
[
1
2
1
]
4
1
[
1 4 6 4 1]
16 1[
1 6 15 20 15 6 1]
64 1MGattass
Gaussiana
2 2 2 22
1
)
,
(
σσ
π
y xe
y
x
G
+ −=
⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ 1 2 1 2 4 2 1 2 1 16 1 ⎥ ⎥ ⎥ ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎢ ⎢ ⎢ ⎣ ⎡ 1 4 7 4 1 4 16 26 16 4 7 26 41 26 7 4 16 26 16 4 1 4 7 4 1 273 1 0.1 0.2 0.3 0.4 0.1 0.2 0.3 0.4 MGattassFiltragem gaussiana
MGattass
Filtro Gaussiano
⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ 1 2 1 2 4 2 1 2 1 16 1 MGattassDetecção de bordas
2
/
)
(
1 1 ' − +−
=
i i if
f
f
⎩
⎨
⎧
<
−
+
−
>
−
+
−
−
+
−
=
+ − + − + −0
)
2
(
0
0
)
2
(
2
1 1 1 1 1 1 '' i i i i i i i i i if
f
f
se
f
f
f
se
f
f
f
f
f(x) |f '(x)| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |f ''(x)|MGattass
Série
de Taylor
) ( ) ( 2 ) ( ) ( ) ( ) ( ) ( " 3 2 ' x x f x O x f x x f x x f +∆ = + ∆ + ∆ + ∆ i i i if
f
f
f
1 ' "2
1
+
+
≅
+Com ∆x=1, f(x)=f
ie f(x+∆x)=f
i+1Com ∆x=-1, f(x)=f
ie f(x+∆x)=f
i-1 i i i if
f
f
f
1 ' "2
1
+
−
≅
− (a) (b) MGattassAproximações para derivadas
(a-b) ⇒
f
'i≅
(
f
i+1−
f
i−1)
/
2
(a+b) ⇒(
2
)
1 1 " − ++
−
−
−
≅
i i i if
f
f
f
f(x) x fi-1 fi fi+1 i+1 i i-1MGattass
Detecção de bordas
⎟
⎟
⎟
⎠
⎞
⎜
⎜
⎜
⎝
⎛
∂
∂
∂
∂
=
∇
y
f
x
f
y
x
f
(
,
)
Gradiente Laplaciano 2 22 22)
,
(
y
f
x
f
y
x
f
∂
∂
+
∂
∂
=
∇
MGattassFiltros de realce de bordas
⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ − − − − 0 1 0 1 4 1 0 1 0 Laplaciano ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ − 0 0 0 0 1 0 1 0 0 ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡− 0 0 0 0 1 0 0 0 1 ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ − − − 1 0 1 2 0 2 1 0 1 4 1 ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡− − − 1 2 1 0 0 0 1 2 1 4 1 Vertical Horizontal Roberts Sobel Gradiente
MGattass
Exemplo de detecção de
arestas
RGB cinza Laplaciano MGattassFiltragem LoG
⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ 1 2 1 2 4 2 1 2 1 16 1 filtro gaussiano ⎥ ⎥ ⎥ ⎦ ⎤ ⎢ ⎢ ⎢ ⎣ ⎡ − − − − 0 1 0 1 4 1 0 1 0 filtro laplaciano L L← 255− B G R L=0.30 +0.59 +0.11Composição de imagens
Transformações e blending
MGattass
MGattass
Animação de sprites
MGattass
Escala por replicação ou
amostragem de pontos
10 x 8 14 x 10 8 x 5 for (xsrc, ysrc∈ Source) { cor = Source (xsrc, ysrc) xdst= (wdst-1)*xsrc/(wsrc- 1) ydst= (hdst-1)*ysrc/(hsrc- 1) Pixel (xdst, ydst, cor) } for (xsrc, ysrc∈ Source) { cor = Source (xsrc, ysrc) xdst= (wdst-1)*xsrc/(wsrc- 1) ydst= (hdst-1)*ysrc/(hsrc- 1) Pixel (xdst, ydst, cor) }/
ampliação red uçãoMGattass
Ampliação/redução
12×8 36×24 ampliação 3×2 redução MGattass bi-linearAmpliação
pelo vizinho mais próximo
for (xdst, ydst ∈ Destination) { xsrc= ROUND((wsrc-1)*xdst/(wdst - 1)) ysrc= ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } for (xdst, ydst∈ Destination) { xsrc = ROUND((wsrc-1)*xdst/(wdst- 1)) ysrc = ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) }
MGattass
Redução
pelo vizinho mais próximo
(caso problema)
for (xdst, ydst ∈ Destination) { xsrc= ROUND((wsrc-1)*xdst/(wdst - 1)) ysrc= ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } for (xdst, ydst∈ Destination) { xsrc = ROUND((wsrc-1)*xdst/(wdst- 1)) ysrc = ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } 256×256 150×150 100×100 Gauss MGattassRedução
pelo vizinho mais próximo
(caso geral)
for (xdst, ydst ∈ Destination) { xsrc= ROUND((wsrc-1)*xdst/(wdst - 1)) ysrc= ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } for (xdst, ydst∈ Destination) { xsrc = ROUND((wsrc-1)*xdst/(wdst- 1)) ysrc = ROUND((hsrc-1)*ydst/(hdst- 1)) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } 300×225 200×150 100×100MGattass
Transformações geométricas rápidas:
Amostragem de pontos
T(xscr,yscr) T-1(x dst,ydst) xscr yscr xdst ydst for (xsrc, ysrc∈ Source) { cor = Source (xsrc, ysrc) xdst= Tx(xsrc, yscr) ydst= Ty(xscr,ysrc)) Pixel (xdst, ydst, cor) } for (xsrc, ysrc∈ Source) { cor = Source (xsrc, ysrc) xdst= Tx(xsrc, yscr) ydst= Ty(xscr,ysrc)) Pixel (xdst, ydst, cor) } for (xdst, ydst∈ Destination) { xsrc= Tx-1(xdst, ydst) ysrc= Ty-1(xdst,ydst) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) } for (xdst, ydst∈ Destination) { xsrc= Tx-1(xdst, ydst) ysrc= Ty-1(xdst,ydst) cor = Source (xsrc, ysrc) Pixel (xdst, ydst, cor) }/
/
quais são os pixels do destino?
MGattass
Determinação dos pixels
do destino
ydst xdst xscr yscrou
:
;
MGattass
Cálculo incremental da
transformação geométrica
x
src= T
x-1(x
dst, y
dst) = a x
dst+ b y
dst+ c
y
src= T
y-1(x
dst,y
dst) = d x
dst+ e y
dst+ f
T
a
b
c
d
e
f
−=
⎡
⎣
⎢
⎢
⎢
⎤
⎦
⎥
⎥
⎥
10
0
1
Suponha que:x
src= T
x-1(x
dst+1, y
dst) = a (x
dst+1)+ b y
dst+ c
y
src= T
y-1(x
dst+1,y
dst) = d (x
dst+1)+ e y
dst+ f
D
xx
src= a
D
xy
src= d
D
xx
src= a
D
xy
src= d
D
D
yx
src= b
yy
src= e
D
yx
src= b
D
yy
src= e
MGattassExigências sobre
transformações de imagens
¾
Translação por zero tem que ser a
identidade;
¾
Sequência de translações deve produzir
o mesmo efeito que uma composta da
origem ao destino;
¾
Escalar por um fator
λ, maior que 1, e
depois escalar por 1/ λ deve produzir a
identidade;
¾
Rotação por uma sequência de ângulos
que totalizem 360
0deve produzir a
MGattass
Composição de imagens
com cor transparente
for (xdst, ydst ∈ Destination) {
xsrc = Tx-1(xdst, ydst)
ysrc = Ty-1(xdst,ydst)
cor = Source (xsrc, ysrc)
if (cor != transparente) Pixel (xdst, ydst, cor)
}
for (xdst, ydst ∈ Destination) {
xsrc = Tx-1(xdst, ydst)
ysrc = Ty-1(xdst,ydst)
cor = Source (xsrc, ysrc)
if (cor != transparente) Pixel (xdst, ydst, cor)
} MGattass
Composição de imagens
com máscaras
0 1 ANDMGattass
Colocação de transparência
no código da cor
R1 G1 B1 A1 R2 G2 B2 A2 source 1 destination Rd Gd Bd Adf( A
1,A
2)
Rd = A1R1+(1-A1)R2 Gd = G1+(1-A1)G2 Bd = B1+(1-A1)B2 Ad= A1+(1-A1)A2 source 2 por exemplo:Compressão e
armazenamento
MGattass
Compressão de imagens
Compressão de
Imagens
Compressão de
Imagens
Sem Perda
Sem Perda
Com Perda
Com Perda
z Preserva exatamente o conteúdo da imagem z Taxas de compressão 3 : 1 z Preserva de forma controlada o nível de qualidade da imagem z Taxas de compressão
que chegam a valores de mais de 100 : 1
MGattass
Métodos de compressão
z Sem perdas
» Run length encoding (RLE) - repetição » Huffman coding - histograma
» Predictive coding - diferenças » Block coding (LZW) - dicionário
zCom perdas
» Truncation coding - reduz a representação » Predictive coding - descarta diferenças altas » Block coding - dicionário aproximado » Transform coding - descarta frequencias altas
MGattass
Processo de compressão e
descompressão
Dados da Imagem Original 32, 45, 57, 68, 23, 100, 98, ... 32, 45, 57, 68, 23, 100, 98, ... Imagem Comprimida 32, 45, 57, 68, 23, 100, 98, ... Dados da Imagem Original Compressão da imagem Imagem Comprimida 32, 45, 57, 68, 23, 100, 98, ... Transporte e/ou Armazenamento Descompressão da imagem
MGattassFundamentos da
Compressão de Imagens
zcodificação
zentre pixels
zpsico-visual
A compressão de uma imagem é obtida
quando se elimina a redundância de:
MGattass
Redundância entre pixels
640 colunas x 480 linhas x 1 byte/pixel = 300 KBytes
480*(1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0) = ~18 Kbytes onde 1 = 32 bytes de preto e 0 = 32 bytes de branco
MGattass
Compressão - RLE
Objetivo
Reduzir a quantidade de dados
redundantes.
Exemplo
AAAAAAxxx
6A3x
Caracterísiticas
Simples e rápido, porém a eficiência
depende da imagem a ser comprimida.
MGattass
Run-Length Encoding
76 76 76 76 76 78 79 79 79 79 80 80 76 | 5 78 | 1 79 | 4 80 | 2 imagem binária 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 7 4 1 . . . 5 MGattassCodificação compacta
( )
( )
número
de
bits
r
p
r
l
k k opt⎟⎟
⎠
⎞
⎜⎜
⎝
⎛
=
log
21
r p(r) Code 1 l(r) l(r)p(r) Code 2 l(r) l(r)p(r) log(1/p) log(1/p)*p
0 0.19 000 3 0.57 11 2 0.38 2.4 0.46 1/7 0.25 001 3 0.75 01 2 0.50 2.0 0.50 2/7 0.21 010 3 0.63 10 2 0.42 2.3 0.47 3/7 0.16 011 3 0.48 001 3 0.48 2.6 0.42 4/7 0.08 100 3 0.24 0001 4 0.32 3.6 0.29 5/7 0.06 101 3 0.18 00001 5 0.30 4.1 0.24 6/7 0.03 110 3 0.09 000001 6 0.18 5.1 0.15 1 0.02 111 3 0.06 000000 6 0.12 5.6 0.11
∑=1.00 Lavg= 3.00 Lavg=2.70 Lopt= 2.65
MGattass
Outra ordem no plano
MGattass
Tipo Abstrato Imagem
/*- implementação do tipo IMAGEM */ struct image_imp {
unsigned short width; /* largura (width) em pixels */ unsigned short height; /* altura (height) em pixels */ unsigned char *buf; /* buffer RGBA */ };
typedef struct image_imp * IMAGE; typedef unsigned char uchar;
IMAGE imgCreate (int w, int h); void imgDestroy (IMAGE img);
void imgGetDimensions(IMAGE img, int *w, int *h);
void imgSetPixel(IMAGE img, int x,int y, uchar r,uchar g,uchar b,uchar a); void imgGetPixel(IMAGE img, int x,int y, uchar *r,uchar *g uchar *b,uchar *a); void imgDraw(IMAGE img);
IMAGE imgReadTGA (char *filename); int imgWriteTGA(char *filename, IMAGE img); Imagem.h
MGattass
Arquivos Targa RGBA
Cabeçalho Pixels (bgra,bgra, …,bgra)
/* escreve o cabecalho */
putc(byteZero,filePtr); /* no. de caracteres no campo de id da imagem */ putc(byteZero,filePtr); /* imagem nao tem palheta de cores */ putc(imageType,filePtr); /* = 2 -> imagem "true color" (RGBA) */ 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(img->width,filePtr); /* largura da imagem em pixels */ putuint(img->height,filePtr); /* altura da imagem em pixels */ putc(bitDepth,filePtr); /* numero de bits de um pixel */
putc(byteZero, filePtr); /* origem canto inf esquedo sem entrelacamento */ unsigned char imageType=2 /* RGB(A) sem compressão */
unsigned char bitDepth=32; /* 32 bits por pixel */
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 */
MGattass
Esquemas de armazenamento de
imagens
Verm. Verde Azul Pix el2Plano de Cores
00 01 02 03 04 05 06 07 08 09 . . . Pix el0 Pix el5 Pix el4 Pix el3 Pix el1 06 06Organização dos pixels de uma imagem por planos de cores Banc os (Jav a) Informação é uma componente da cor
MGattass
Organização de pixels num array
no formato TGA (targa)
b g r a b g r a b g r a b 0 1 … ... a r g w-1
x
y
unsigned char *bgra_vector; … offset=4*(w*y+x); blue = bgra_vector[offset]; green = bgra_vector[offset+1]; red = bgra_vector[offset+2]; alpha = bgra_vector[offset+3]; 0 1 2 h-1 3 Pixel (x,y) MGattass
Organização de pixels num array
no formato PPM (o mais simples)
00 01 02 03 04 05 06 07 08 0910 11 0 1 2 ... 13 12 14 w-1 15 16 17 18 ...
x
y
Pixel (x,y)unsigned char *rgb_vector; … offset=3*(w*y+x); red = rgb_vector[offset]; green = rgb_vector[offset+1]; blue = rgb_vector[offset+2]; 0 1 2 h-1 3 ...
MGattass
Formato PPM
• File_signature "P6".
• White_space (blanks, TABs, CRs, LFs).
• Width, w, (ASCII decimal characters).
• White_space (blanks, TABs, CRs, LFs).
• Height, h, (ASCII decimal characters).
• White_space (blanks, TABs, CRs, LFs).
• Max_color, max, (ASCII decimal characters).
• White_space (blanks, TABs, CRs, LFs).
• Pixels, (3*w*h bytes rgb components of pixels)
• Comments from # to the end of line
• lines ≤ 70 characters
MGattass
Formato PPM
P6
# Created by Paint Shop Pro
358 539
255
=?:?A<AC>CE@EFAFGBGHCGHCGHB . . .
MGattass
Gravação em PPM
int ppm_write(int w, int h, unsigned char *rgb, char *file_name) { FILE *fp; fp = fopen(file_name, "wb"); if (fp == NULL) return 0; if (fprintf(fp, "P6\n%d %d\n255\n", w, h) <= 0) { fclose(fp); return 0; } if (fwrite(rgb, 3*w*h, 1, fp) != 1) { fclose(fp); return 0; } fclose(fp); return 1; }
Leitura em PPM
int ppm_read(int *p_w, int *p_h, unsigned char **p_rgb, char *file_name) {
FILE *fp; char line[80]; int rgb_size; int max; fp = fopen(file_name, "rb");
if (fp == NULL) {
printf(”Error reading %s",file_name); return 0;} fgets(line,80,fp);
if(strcmp(line,"P6\n")) {
printf(”Wrong signature\n"); return 0; } while (fscanf( fp, " %d ", p_w ) != 1)
fgets(line, 80, fp);
while (fscanf( fp, " %d ", p_h ) != 1) fgets(line, 80, fp);
while (fscanf( fp, " %d", &max ) != 1) fgets(line, 80, fp);
fgetc(fp);
rgb_size=3*(*p_w)*(*p_h);
(*p_rgb) = (unsigned char *) calloc(rgb_size, 1); if ((*p_rgb) != NULL)
fread( (*p_rgb), rgb_size, 1, fp ); fclose(fp);
return 1; }
Programa Simples
void main(void){
int w, h; // dimensões da imagem unsigned char *rgb; // bytes de rgb
unsigned char r,g,b,grey; // componentes de cor int x,y; long int k;
if (ppm_read(&w,&h,&rgb,"test_in.ppm")==0) return; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { k = 3*(y*w+x); r = rgb[k]; g = rgb[k+1]; b = rgb[k+2];
grey = (unsigned char)(0.3*r+0.6*g+0.1*b); rgb[k] = grey; rgb[k+1] = grey; rgb[k+2] = grey; } } ppm_write(w, h, rgb, "test_out.ppm"); free(rgb); } MGattass
Arquivo BMP
00 01 02 03 04 05 06 07 08 09 10 11Pixel 0 Pixel 1 Pixel 2 Pixel 3
13
12 14
Pixel 4
15
16 17 18 ...
colocado para garantir múltiplo de 4
colocado para garantir múltiplo de 4
Organização dos pixels de uma imagem RGB no arquivo BMP
MGattass
Microsoft Windows
Bitmap - BMP
Características Principais
zMono, 4-bit, 8-bit, 24-bit
zTipo de compressão: RLE / não comprimido
zTamanho máximo: 64K x 64K pixels
zSeções (versão 3): Header Info. Header Palette Bitmap Data MGattass
BMP - Header
typedef struct _Win3xBitmapHeader {
WORD Type; /* Image file type 4D42h (“BM”)*/
DWORD FileSize; /* File size (bytes) */ WORD Reserved1; /* Reserved (always 0) */ WORD Reserved2; /* Reserved (always 0) */
DWORD Offset; /* Offset to bitmap data in bytes */
MGattass
BMP - Information Header
typedef struct _Win3xBitmapInfoHeader {
DWORD Size; /* Size of this Header (40) */
DWORD Width; /* Image width (pixels) */
DWORD Height; /* Image height (pixels) */
WORD Planes; /* Number of Planes (always=1) */
WORD BitCount; /* Bits per pixel (1/4/8 or 24)*/ DWORD Compression; /* Compression (0/1/2) */ DWORD SizeImage; /* Size of bitmap (bytes) */
DWORD XPelsPerMeter; /* Horz. resol.(pixels/m) */
DWORD YPelsPerMeter; /* Vert. resol.(pixels/m) */ DWORD ClrUsed; /* Num of colors in the image */ DWORD ClrImportant; /* Num of important colors */ } WIN3XINFOHEADER;
MGattass
BMP - Palette
typedef struct _Win3xPalette {
RGBQUAD Palette[ ]; /* 2, 16, or 256 elem.*/ } WIN3XPALETTE;
typedef struct _Win3xRgbQuad {
BYTE Blue; /* 8-bit blue component */
BYTE Green; /* 8-bit green component */
BYTE Red; /* 8-bit red component */
BYTE Reserved; /* Reserved (= 0)
*/
MGattass
BMP - Image Data
Notas
Cada scan line em um arquivo BMP é sempre um múltiplo de 4.
Imagens com1-, 4-, e 8-bits usam uma palheta de cores.
Imagens com 24-bits guardam a cor diretamente, na ordem azul, verde e vermelho.
O armazenamento da imagem é sempre feito a partir do canto esquerdo inferior.