]> gitweb.factorcode.org Git - factor.git/blob - basis/images/normalization/normalization.factor
2bd7e6883ffb7ba93e8947ab0323ae67aeb31d56
[factor.git] / basis / images / normalization / normalization.factor
1 ! Copyright (C) 2009 Doug Coleman, Keith Lazuka
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types byte-arrays combinators fry
4 grouping images kernel locals math math.vectors
5 sequences specialized-arrays half-floats ;
6 FROM: alien.c-types => float ;
7 SPECIALIZED-ARRAY: half
8 SPECIALIZED-ARRAY: float
9 SPECIALIZED-ARRAY: ushort
10 IN: images.normalization
11
12 <PRIVATE
13
14 CONSTANT: don't-care 127
15 CONSTANT: fill-value 255
16
17 : permutation ( src dst -- seq )
18     swap '[ _ index [ don't-care ] unless* ] { } map-as
19     4 don't-care pad-tail ;
20
21 : pad4 ( seq -- newseq ) 4 fill-value pad-tail ;
22
23 : shuffle ( seq permutation -- newseq )
24     swap '[
25         dup 4 >= [ drop fill-value ] [ _ nth ] if
26     ] B{ } map-as ;
27
28 :: permute ( bytes src-order dst-order -- new-bytes )
29     src-order name>> :> src
30     dst-order name>> :> dst
31     bytes src length group
32     [ pad4 src dst permutation shuffle dst length head ]
33     map concat ;
34
35 : (reorder-components) ( image src-order dest-order -- image )
36     [ permute ] 2curry change-bitmap ;
37
38 GENERIC: normalize-component-type* ( image component-type -- image )
39
40 : normalize-floats ( float-array -- byte-array )
41     [ 255.0 * >integer ] B{ } map-as ;
42
43 M: float-components normalize-component-type*
44     drop byte-array>float-array normalize-floats ;
45
46 M: half-components normalize-component-type*
47     drop byte-array>half-array normalize-floats ;
48
49 : ushorts>ubytes ( bitmap -- bitmap' )
50     byte-array>ushort-array [ -8 shift ] B{ } map-as ; inline
51
52 M: ushort-components normalize-component-type*
53     drop ushorts>ubytes ;
54
55 M: ubyte-components normalize-component-type*
56     drop ;
57
58 : normalize-scan-line-order ( image -- image )
59     dup upside-down?>> [
60         dup dim>> first 4 * '[
61             _ <groups> reverse concat
62         ] change-bitmap
63         f >>upside-down?
64     ] when ;
65
66 : validate-request ( src-order dst-order -- src-order dst-order )
67     [
68         [ { DEPTH DEPTH-STENCIL INTENSITY } member? ] bi@
69         or [ "Invalid component-order" throw ] when
70     ] 2keep ;
71
72 PRIVATE>
73
74 : reorder-components ( image component-order -- image )
75     [
76         dup component-type>> '[ _ normalize-component-type* ] change-bitmap
77         dup component-order>>
78     ] dip
79     validate-request [ (reorder-components) ] keep >>component-order ;
80
81 : normalize-image ( image -- image )
82     [ >byte-array ] change-bitmap
83     RGBA reorder-components
84     normalize-scan-line-order ;
85