hansu 0.3.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hansu/__init__.py +18 -0
- hansu/_arith.py +152 -0
- hansu/_backend.py +16 -0
- hansu/_fast.py +41 -0
- hansu/_hs_ac.c +228 -0
- hansu/_yco.py +12 -0
- hansu/build_c.py +20 -0
- hansu/cli.py +102 -0
- hansu/codec.py +339 -0
- hansu/idx2d.py +130 -0
- hansu/index.py +27 -0
- hansu/palette.py +29 -0
- hansu/standalone.py +268 -0
- hansu/tilepal.py +121 -0
- hansu/topology.py +73 -0
- hansu-0.3.0.dist-info/METADATA +279 -0
- hansu-0.3.0.dist-info/RECORD +21 -0
- hansu-0.3.0.dist-info/WHEEL +5 -0
- hansu-0.3.0.dist-info/entry_points.txt +2 -0
- hansu-0.3.0.dist-info/licenses/LICENSE +21 -0
- hansu-0.3.0.dist-info/top_level.txt +1 -0
hansu/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""hansu — a structural image codec with topology signatures.
|
|
3
|
+
|
|
4
|
+
from hansu import encode, decode
|
|
5
|
+
data, rec = encode(img) # img: HxWx3 or HxWx4 uint8
|
|
6
|
+
img2 = decode(data)
|
|
7
|
+
|
|
8
|
+
Format: HS2 v5 (docs/HS2-format.md). Pure-Python reference coder included;
|
|
9
|
+
optional C backend via `python -m hansu.build_c`.
|
|
10
|
+
"""
|
|
11
|
+
__version__ = "0.3.0"
|
|
12
|
+
|
|
13
|
+
from .codec import encode, decode, encode_banded, decode_banded, encode_auto, decode_any
|
|
14
|
+
from .topology import signature, distance
|
|
15
|
+
from .standalone import decode as decode_reference
|
|
16
|
+
from . import _backend as _b
|
|
17
|
+
|
|
18
|
+
BACKEND = _b.NAME
|
hansu/_arith.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Pure-Python reference entropy coder (MED prediction + 250-context binary arithmetic coding).
|
|
3
|
+
|
|
4
|
+
This is the normative reference implementation. It is bit-exact with the C
|
|
5
|
+
backend in ``_fast``; it is slower, and exists so the format can be used,
|
|
6
|
+
audited and re-implemented without a compiler.
|
|
7
|
+
"""
|
|
8
|
+
import numpy as np
|
|
9
|
+
|
|
10
|
+
HALF = 0x80000000; FQ = 0x40000000; TQ = 0xC0000000
|
|
11
|
+
NB = 32
|
|
12
|
+
|
|
13
|
+
class _AE:
|
|
14
|
+
__slots__ = ("low", "high", "pending", "bits")
|
|
15
|
+
def __init__(self):
|
|
16
|
+
self.low = 0; self.high = 0xFFFFFFFF; self.pending = 0; self.bits = []
|
|
17
|
+
def _out(self, b):
|
|
18
|
+
self.bits.append(b)
|
|
19
|
+
for _ in range(self.pending): self.bits.append(1 - b)
|
|
20
|
+
self.pending = 0
|
|
21
|
+
def bit(self, p0, b):
|
|
22
|
+
rng = self.high - self.low + 1
|
|
23
|
+
bound = (rng * p0) >> 12
|
|
24
|
+
if bound < 1: bound = 1
|
|
25
|
+
if bound >= rng: bound = rng - 1
|
|
26
|
+
if b == 0: self.high = self.low + bound - 1
|
|
27
|
+
else: self.low = self.low + bound
|
|
28
|
+
while True:
|
|
29
|
+
if self.high < HALF: self._out(0)
|
|
30
|
+
elif self.low >= HALF: self._out(1); self.low -= HALF; self.high -= HALF
|
|
31
|
+
elif self.low >= FQ and self.high < TQ: self.pending += 1; self.low -= FQ; self.high -= FQ
|
|
32
|
+
else: break
|
|
33
|
+
self.low = (self.low << 1) & 0xFFFFFFFF; self.high = ((self.high << 1) | 1) & 0xFFFFFFFF
|
|
34
|
+
def finish(self):
|
|
35
|
+
self.pending += 1
|
|
36
|
+
self._out(0) if self.low < FQ else self._out(1)
|
|
37
|
+
return bytes(bytearray(np.packbits(np.array(self.bits, np.uint8)).tolist()))
|
|
38
|
+
|
|
39
|
+
class _AD:
|
|
40
|
+
__slots__ = ("bits", "pos", "low", "high", "code")
|
|
41
|
+
def __init__(self, data):
|
|
42
|
+
self.bits = np.unpackbits(np.frombuffer(data, np.uint8)); self.pos = 0
|
|
43
|
+
self.low = 0; self.high = 0xFFFFFFFF; self.code = 0
|
|
44
|
+
for _ in range(32):
|
|
45
|
+
self.code = (self.code << 1) | int(self._next())
|
|
46
|
+
def _next(self):
|
|
47
|
+
if self.pos < len(self.bits):
|
|
48
|
+
b = int(self.bits[self.pos]); self.pos += 1; return b
|
|
49
|
+
self.pos += 1; return 0
|
|
50
|
+
def bit(self, p0):
|
|
51
|
+
rng = self.high - self.low + 1
|
|
52
|
+
bound = (rng * p0) >> 12
|
|
53
|
+
if bound < 1: bound = 1
|
|
54
|
+
if bound >= rng: bound = rng - 1
|
|
55
|
+
if self.code - self.low < bound:
|
|
56
|
+
b = 0; self.high = self.low + bound - 1
|
|
57
|
+
else:
|
|
58
|
+
b = 1; self.low = self.low + bound
|
|
59
|
+
while True:
|
|
60
|
+
if self.high < HALF: pass
|
|
61
|
+
elif self.low >= HALF: self.low -= HALF; self.high -= HALF; self.code -= HALF
|
|
62
|
+
elif self.low >= FQ and self.high < TQ: self.low -= FQ; self.high -= FQ; self.code -= FQ
|
|
63
|
+
else: break
|
|
64
|
+
self.low = (self.low << 1) & 0xFFFFFFFF; self.high = ((self.high << 1) | 1) & 0xFFFFFFFF
|
|
65
|
+
self.code = ((self.code << 1) & 0xFFFFFFFF) | self._next()
|
|
66
|
+
return b
|
|
67
|
+
|
|
68
|
+
def _q5(v):
|
|
69
|
+
if v < -6: return -2
|
|
70
|
+
if v < -2: return -1
|
|
71
|
+
if v <= 2: return 0
|
|
72
|
+
if v <= 6: return 1
|
|
73
|
+
return 2
|
|
74
|
+
|
|
75
|
+
def _ctx(rec, y, x):
|
|
76
|
+
if y == 0: return 0, (rec[0, x-1] if x > 0 else 128)
|
|
77
|
+
if x == 0: return 0, int(rec[y-1, 0])
|
|
78
|
+
a = int(rec[y, x-1]); b = int(rec[y-1, x]); c = int(rec[y-1, x-1])
|
|
79
|
+
pred = min(a, b) if c >= max(a, b) else (max(a, b) if c <= min(a, b) else a + b - c)
|
|
80
|
+
d1 = int(rec[y-1, x]) - int(rec[y-1, x-1])
|
|
81
|
+
d2 = int(rec[y-1, x-1]) - int(rec[y, x-1])
|
|
82
|
+
d3 = int(rec[y, x-1]) - int(rec[y-1, x])
|
|
83
|
+
act = 1 if (abs(d1) + abs(d2) + abs(d3)) > 8 else 0
|
|
84
|
+
ctx = (((_q5(d1) + 2) * 5 + (_q5(d2) + 2)) * 5 + (_q5(d3) + 2)) * 2 + act
|
|
85
|
+
return ctx, pred
|
|
86
|
+
|
|
87
|
+
def encode(g, q=1):
|
|
88
|
+
"""g: 2-D uint8 array. Returns compressed bytes."""
|
|
89
|
+
h, w = g.shape
|
|
90
|
+
g = np.asarray(g, np.int32); rec = g.copy()
|
|
91
|
+
N0 = np.ones(250 * NB, np.int32); N1 = np.ones(250 * NB, np.int32)
|
|
92
|
+
enc = _AE()
|
|
93
|
+
q = int(q)
|
|
94
|
+
p0of = lambda i: max(1, min(4095, int((int(N0[i]) << 12) // int(N0[i] + N1[i]))))
|
|
95
|
+
for y in range(h):
|
|
96
|
+
for x in range(w):
|
|
97
|
+
ctx, pred = _ctx(rec, y, x)
|
|
98
|
+
rq = int(round((int(g[y, x]) - pred) / q))
|
|
99
|
+
rec[y, x] = max(0, min(255, pred + rq * q))
|
|
100
|
+
k = abs(rq).bit_length(); kk = min(k, 12); base = ctx * NB
|
|
101
|
+
for i in range(kk + 1):
|
|
102
|
+
idx = base + min(i, 12); bt = 1 if i < kk else 0
|
|
103
|
+
enc.bit(p0of(idx), bt)
|
|
104
|
+
if bt == 0: N0[idx] += 1
|
|
105
|
+
else: N1[idx] += 1
|
|
106
|
+
if kk > 1:
|
|
107
|
+
for i in range(kk - 2, -1, -1):
|
|
108
|
+
idx = base + 18 + min(i, 7); bt = (abs(rq) >> i) & 1
|
|
109
|
+
enc.bit(p0of(idx), bt)
|
|
110
|
+
if bt == 0: N0[idx] += 1
|
|
111
|
+
else: N1[idx] += 1
|
|
112
|
+
if rq != 0:
|
|
113
|
+
idx = base + 26; bt = 1 if rq < 0 else 0
|
|
114
|
+
enc.bit(p0of(idx), bt)
|
|
115
|
+
if bt == 0: N0[idx] += 1
|
|
116
|
+
else: N1[idx] += 1
|
|
117
|
+
return enc.finish()
|
|
118
|
+
|
|
119
|
+
def decode(stream, h, w, q=1):
|
|
120
|
+
"""stream bytes -> 2-D uint8 array of shape (h, w)."""
|
|
121
|
+
q = float(q); dec = _AD(stream); rec = np.zeros((h, w), np.int32)
|
|
122
|
+
N0 = np.ones(250 * NB, np.int32); N1 = np.ones(250 * NB, np.int32)
|
|
123
|
+
p0of = lambda i: max(1, min(4095, int((int(N0[i]) << 12) // int(N0[i] + N1[i]))))
|
|
124
|
+
for y in range(h):
|
|
125
|
+
for x in range(w):
|
|
126
|
+
ctx, pred = _ctx(rec, y, x)
|
|
127
|
+
base = ctx * NB; kk = 0
|
|
128
|
+
while True:
|
|
129
|
+
idx = base + min(kk, 12); bt = dec.bit(p0of(idx))
|
|
130
|
+
if bt == 1:
|
|
131
|
+
N1[idx] += 1; kk += 1
|
|
132
|
+
if kk > 12: break
|
|
133
|
+
else:
|
|
134
|
+
N0[idx] += 1; break
|
|
135
|
+
mag = 0
|
|
136
|
+
if kk > 1:
|
|
137
|
+
for i in range(kk - 2, -1, -1):
|
|
138
|
+
idx = base + 18 + min(i, 7); bt = dec.bit(p0of(idx)); mag = (mag << 1) | bt
|
|
139
|
+
if bt == 0: N0[idx] += 1
|
|
140
|
+
else: N1[idx] += 1
|
|
141
|
+
mag |= (1 << (kk - 1))
|
|
142
|
+
elif kk == 1:
|
|
143
|
+
mag = 1
|
|
144
|
+
if mag > 0:
|
|
145
|
+
idx = base + 26; sg = dec.bit(p0of(idx))
|
|
146
|
+
if sg == 0: N0[idx] += 1
|
|
147
|
+
else: N1[idx] += 1
|
|
148
|
+
rq = -mag if sg else mag
|
|
149
|
+
else:
|
|
150
|
+
rq = 0
|
|
151
|
+
rec[y, x] = max(0, min(255, int(round(pred + rq * q))))
|
|
152
|
+
return rec.astype(np.uint8)
|
hansu/_backend.py
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Pick the C backend when built, else the pure-Python reference implementation."""
|
|
3
|
+
from . import _arith
|
|
4
|
+
|
|
5
|
+
try:
|
|
6
|
+
from . import _fast
|
|
7
|
+
if _fast.available():
|
|
8
|
+
encode = _fast.encode
|
|
9
|
+
decode = _fast.decode
|
|
10
|
+
NAME = "c"
|
|
11
|
+
else:
|
|
12
|
+
raise ImportError
|
|
13
|
+
except Exception:
|
|
14
|
+
encode = _arith.encode
|
|
15
|
+
decode = _arith.decode
|
|
16
|
+
NAME = "py"
|
hansu/_fast.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""C backend (optional). Built at install time when a compiler is available."""
|
|
3
|
+
import ctypes, os
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
_lib = None
|
|
7
|
+
def _load():
|
|
8
|
+
global _lib
|
|
9
|
+
if _lib is not None: return _lib
|
|
10
|
+
name = "_hs_ac_c.so" if os.name != "nt" else "_hs_ac_c.dll"
|
|
11
|
+
path = os.path.join(os.path.dirname(os.path.abspath(__file__)), name)
|
|
12
|
+
if not os.path.exists(path):
|
|
13
|
+
raise ImportError("C backend not built; run `python -m hansu.build_c`")
|
|
14
|
+
_lib = ctypes.CDLL(path)
|
|
15
|
+
_lib.hs_encode.argtypes = [ctypes.POINTER(ctypes.c_uint8), ctypes.c_int, ctypes.c_int,
|
|
16
|
+
ctypes.c_int, ctypes.POINTER(ctypes.c_uint8)]
|
|
17
|
+
_lib.hs_encode.restype = ctypes.c_size_t
|
|
18
|
+
_lib.hs_decode.argtypes = [ctypes.POINTER(ctypes.c_uint8), ctypes.c_size_t, ctypes.c_int,
|
|
19
|
+
ctypes.c_int, ctypes.c_int, ctypes.POINTER(ctypes.c_uint8)]
|
|
20
|
+
_lib.hs_decode.restype = None
|
|
21
|
+
return _lib
|
|
22
|
+
|
|
23
|
+
def available():
|
|
24
|
+
try:
|
|
25
|
+
_load(); return True
|
|
26
|
+
except Exception:
|
|
27
|
+
return False
|
|
28
|
+
|
|
29
|
+
def encode(g, q=1):
|
|
30
|
+
lib = _load()
|
|
31
|
+
g = np.ascontiguousarray(g, np.uint8); h, w = g.shape
|
|
32
|
+
out = (ctypes.c_uint8 * (w * h * 5 + 64))()
|
|
33
|
+
nb = lib.hs_encode(g.ctypes.data_as(ctypes.POINTER(ctypes.c_uint8)), w, h, int(q), out)
|
|
34
|
+
return bytes(out[:nb])
|
|
35
|
+
|
|
36
|
+
def decode(stream, h, w, q=1):
|
|
37
|
+
lib = _load()
|
|
38
|
+
buf = (ctypes.c_uint8 * len(stream)).from_buffer_copy(stream)
|
|
39
|
+
rec = (ctypes.c_uint8 * (w * h))()
|
|
40
|
+
lib.hs_decode(buf, len(stream), w, h, int(q), rec)
|
|
41
|
+
return np.frombuffer(bytes(rec), np.uint8).reshape(h, w).copy()
|
hansu/_hs_ac.c
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/* 珩速上下文算术编码器 —— C 版,与 上下文算术3.py / 算术解码.py bit-exact */
|
|
2
|
+
#include <stdint.h>
|
|
3
|
+
#include <stdlib.h>
|
|
4
|
+
#include <string.h>
|
|
5
|
+
#include <math.h>
|
|
6
|
+
|
|
7
|
+
#define HALF 0x80000000u
|
|
8
|
+
#define FQ 0x40000000u
|
|
9
|
+
#define TQ 0xC0000000u
|
|
10
|
+
#define NB 32
|
|
11
|
+
#define NCTX 250
|
|
12
|
+
#define NTOT (NCTX*NB)
|
|
13
|
+
static size_t g_last_bits = 0;
|
|
14
|
+
size_t hs_last_bits(void){ return g_last_bits; }
|
|
15
|
+
|
|
16
|
+
typedef struct {
|
|
17
|
+
uint64_t low, high; uint32_t pending;
|
|
18
|
+
uint8_t *buf; size_t pos, cap;
|
|
19
|
+
uint8_t cur; int nbits;
|
|
20
|
+
} AE;
|
|
21
|
+
|
|
22
|
+
static void ae_init(AE *e, size_t cap){
|
|
23
|
+
e->low=0; e->high=0xFFFFFFFFu; e->pending=0;
|
|
24
|
+
e->pos=0; e->cap=cap; e->cur=0; e->nbits=0;
|
|
25
|
+
e->buf=(uint8_t*)malloc(cap);
|
|
26
|
+
}
|
|
27
|
+
static void put_bit(AE *e, int b){
|
|
28
|
+
e->cur=(uint8_t)((e->cur<<1)|(uint8_t)b); e->nbits++;
|
|
29
|
+
if(e->nbits==8){ if(e->pos<e->cap) e->buf[e->pos++]=e->cur; e->cur=0; e->nbits=0; }
|
|
30
|
+
}
|
|
31
|
+
static void flush_byte(AE *e){
|
|
32
|
+
if(e->nbits>0){ e->cur=(uint8_t)(e->cur<<(8-e->nbits)); if(e->pos<e->cap) e->buf[e->pos++]=e->cur; e->cur=0; e->nbits=0; }
|
|
33
|
+
}
|
|
34
|
+
static void out_bit(AE *e, int b){
|
|
35
|
+
put_bit(e,b);
|
|
36
|
+
int p=(int)e->pending;
|
|
37
|
+
for(int i=0;i<p;i++) put_bit(e,1-b);
|
|
38
|
+
e->pending=0;
|
|
39
|
+
}
|
|
40
|
+
static void ae_bit(AE *e, int p0, int b){
|
|
41
|
+
uint64_t rng=e->high-e->low+1u;
|
|
42
|
+
uint64_t bound=(rng*(uint64_t)p0)>>12;
|
|
43
|
+
if(bound<1u) bound=1u;
|
|
44
|
+
if(bound>=rng) bound=rng-1u;
|
|
45
|
+
if(b==0) e->high=e->low+bound-1u;
|
|
46
|
+
else e->low=e->low+bound;
|
|
47
|
+
for(;;){
|
|
48
|
+
if(e->high<HALF){ out_bit(e,0); }
|
|
49
|
+
else if(e->low>=HALF){ out_bit(e,1); e->low-=HALF; e->high-=HALF; }
|
|
50
|
+
else if(e->low>=FQ && e->high<TQ){ e->pending++; e->low-=FQ; e->high-=FQ; }
|
|
51
|
+
else break;
|
|
52
|
+
e->low=(e->low<<1)&0xFFFFFFFFu; e->high=((e->high<<1)|1u)&0xFFFFFFFFu;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
static int q5(int v){
|
|
56
|
+
if(v<-6) return -2;
|
|
57
|
+
if(v<-2) return -1;
|
|
58
|
+
if(v<=2) return 0;
|
|
59
|
+
if(v<=6) return 1;
|
|
60
|
+
return 2;
|
|
61
|
+
}
|
|
62
|
+
static int enc_bin(AE *e, int32_t *N0, int32_t *N1, int idx, int bt){
|
|
63
|
+
int32_t n0=N0[idx], n1=N1[idx];
|
|
64
|
+
int p0=(int)(((int64_t)n0<<12)/(int64_t)(n0+n1));
|
|
65
|
+
if(p0<1) p0=1; if(p0>4095) p0=4095;
|
|
66
|
+
ae_bit(e,p0,bt);
|
|
67
|
+
if(bt==0) N0[idx]=n0+1; else N1[idx]=n1+1;
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/* 返回流字节数,out 需调用方分配 (n*n*5+64) */
|
|
72
|
+
size_t hs_encode(const uint8_t *g, int w, int h, int q, uint8_t *out){
|
|
73
|
+
AE e; ae_init(&e, (size_t)w*h*5+64);
|
|
74
|
+
int32_t *N0=(int32_t*)malloc(sizeof(int32_t)*NTOT);
|
|
75
|
+
int32_t *N1=(int32_t*)malloc(sizeof(int32_t)*NTOT);
|
|
76
|
+
for(int i=0;i<NTOT;i++){ N0[i]=1; N1[i]=1; }
|
|
77
|
+
int16_t *rec=(int16_t*)malloc(sizeof(int16_t)*w*h);
|
|
78
|
+
for(int y=0;y<h;y++){
|
|
79
|
+
for(int x=0;x<w;x++){
|
|
80
|
+
int pred;
|
|
81
|
+
if(y==0) pred = (x>0)? rec[x-1] : 128;
|
|
82
|
+
else if(x==0) pred = rec[(y-1)*w];
|
|
83
|
+
else {
|
|
84
|
+
int a=rec[y*w+x-1], b=rec[(y-1)*w+x], c=rec[(y-1)*w+x-1];
|
|
85
|
+
pred = (c>=((a>b)?a:b)) ? ((a<b)?a:b) : ((c<=((a<b)?a:b)) ? ((a>b)?a:b) : a+b-c);
|
|
86
|
+
}
|
|
87
|
+
int ctx=0;
|
|
88
|
+
if(y>0&&x>0){
|
|
89
|
+
int d1=rec[(y-1)*w+x]-rec[(y-1)*w+x-1];
|
|
90
|
+
int d2=rec[(y-1)*w+x-1]-rec[y*w+x-1];
|
|
91
|
+
int d3=rec[y*w+x-1]-rec[(y-1)*w+x];
|
|
92
|
+
int act=((abs(d1)+abs(d2)+abs(d3))>8)?1:0;
|
|
93
|
+
ctx=(((q5(d1)+2)*5+(q5(d2)+2))*5+(q5(d3)+2))*2+act;
|
|
94
|
+
}
|
|
95
|
+
int val=(int)g[y*w+x];
|
|
96
|
+
int rq=(int)nearbyint((double)(val-pred)/(double)q);
|
|
97
|
+
int rv=pred+rq*q; if(rv<0) rv=0; if(rv>255) rv=255;
|
|
98
|
+
rec[y*w+x]=(int16_t)rv;
|
|
99
|
+
int k=0, t=rq<0?-rq:rq; while(t){ k++; t>>=1; }
|
|
100
|
+
int kk=(k>12)?12:k;
|
|
101
|
+
int base=ctx*NB;
|
|
102
|
+
for(int i=0;i<=kk;i++){
|
|
103
|
+
int idx=base+(i<12?i:12);
|
|
104
|
+
int bt=(i<kk)?1:0;
|
|
105
|
+
enc_bin(&e,N0,N1,idx,bt);
|
|
106
|
+
}
|
|
107
|
+
if(kk>1){
|
|
108
|
+
for(int i=kk-2;i>=0;i--){
|
|
109
|
+
int idx=base+18+(i<7?i:7);
|
|
110
|
+
int bt=((rq<0?-rq:rq)>>i)&1;
|
|
111
|
+
enc_bin(&e,N0,N1,idx,bt);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
if(rq!=0){
|
|
115
|
+
int idx=base+26;
|
|
116
|
+
int bt=(rq<0)?1:0;
|
|
117
|
+
enc_bin(&e,N0,N1,idx,bt);
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
e.pending++;
|
|
122
|
+
if(e.low<FQ) out_bit(&e,0); else out_bit(&e,1);
|
|
123
|
+
g_last_bits = e.pos*8 + e.nbits;
|
|
124
|
+
flush_byte(&e);
|
|
125
|
+
size_t len=e.pos;
|
|
126
|
+
if(e.cap<len) len=e.cap;
|
|
127
|
+
memcpy(out,e.buf,len);
|
|
128
|
+
free(e.buf); free(N0); free(N1); free(rec);
|
|
129
|
+
return len;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
typedef struct {
|
|
133
|
+
const uint8_t *buf; size_t pos; long bitpos;
|
|
134
|
+
} BD;
|
|
135
|
+
static int get_bit(BD *d){
|
|
136
|
+
size_t byte=d->bitpos>>3; int off=7-(int)(d->bitpos&7);
|
|
137
|
+
d->bitpos++;
|
|
138
|
+
if(byte>=d->pos) return 0;
|
|
139
|
+
return (d->buf[byte]>>off)&1;
|
|
140
|
+
}
|
|
141
|
+
static void ae_init_dec(uint64_t *low, uint64_t *high){
|
|
142
|
+
*low=0; *high=0xFFFFFFFFu;
|
|
143
|
+
}
|
|
144
|
+
static int ae_bit_dec(BD *d, uint64_t *low, uint64_t *high, int p0, uint64_t *value){
|
|
145
|
+
uint64_t rng=*high-*low+1u;
|
|
146
|
+
uint64_t bound=(rng*(uint64_t)p0)>>12;
|
|
147
|
+
if(bound<1u) bound=1u;
|
|
148
|
+
if(bound>=rng) bound=rng-1u;
|
|
149
|
+
int b;
|
|
150
|
+
if(*value < *low+bound){ *high=*low+bound-1u; b=0; }
|
|
151
|
+
else { *low=*low+bound; b=1; }
|
|
152
|
+
for(;;){
|
|
153
|
+
if(*high<HALF){ }
|
|
154
|
+
else if(*low>=HALF){ *low-=HALF; *high-=HALF; *value-=HALF; }
|
|
155
|
+
else if(*low>=FQ && *high<TQ){ *low-=FQ; *high-=FQ; *value-=FQ; }
|
|
156
|
+
else break;
|
|
157
|
+
*low=(*low<<1)&0xFFFFFFFFu; *high=((*high<<1)|1u)&0xFFFFFFFFu;
|
|
158
|
+
*value=((*value<<1)|(uint64_t)get_bit(d))&0xFFFFFFFFu;
|
|
159
|
+
}
|
|
160
|
+
return b;
|
|
161
|
+
}
|
|
162
|
+
static int dec_bin(BD *d, uint64_t *low, uint64_t *high, uint64_t *value, int32_t *N0, int32_t *N1, int idx, int *bt){
|
|
163
|
+
int32_t n0=N0[idx], n1=N1[idx];
|
|
164
|
+
int p0=(int)(((int64_t)n0<<12)/(int64_t)(n0+n1));
|
|
165
|
+
if(p0<1) p0=1; if(p0>4095) p0=4095;
|
|
166
|
+
int b=ae_bit_dec(d,low,high,p0,value);
|
|
167
|
+
if(b==0) N0[idx]=n0+1; else N1[idx]=n1+1;
|
|
168
|
+
*bt=b;
|
|
169
|
+
return 0;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
void hs_decode(const uint8_t *stream, size_t len, int w, int h, int q, uint8_t *rec_out){
|
|
173
|
+
BD d; d.buf=stream; d.pos=len; d.bitpos=0;
|
|
174
|
+
uint64_t low, high, value=0;
|
|
175
|
+
ae_init_dec(&low,&high);
|
|
176
|
+
for(int i=0;i<32;i++) value=((value<<1)|(uint64_t)get_bit(&d))&0xFFFFFFFFu;
|
|
177
|
+
int32_t *N0=(int32_t*)malloc(sizeof(int32_t)*NTOT);
|
|
178
|
+
int32_t *N1=(int32_t*)malloc(sizeof(int32_t)*NTOT);
|
|
179
|
+
for(int i=0;i<NTOT;i++){ N0[i]=1; N1[i]=1; }
|
|
180
|
+
int16_t *rec=(int16_t*)malloc(sizeof(int16_t)*w*h);
|
|
181
|
+
for(int y=0;y<h;y++){
|
|
182
|
+
for(int x=0;x<w;x++){
|
|
183
|
+
int pred;
|
|
184
|
+
if(y==0) pred = (x>0)? rec[x-1] : 128;
|
|
185
|
+
else if(x==0) pred = rec[(y-1)*w];
|
|
186
|
+
else {
|
|
187
|
+
int a=rec[y*w+x-1], b=rec[(y-1)*w+x], c=rec[(y-1)*w+x-1];
|
|
188
|
+
pred = (c>=((a>b)?a:b)) ? ((a<b)?a:b) : ((c<=((a<b)?a:b)) ? ((a>b)?a:b) : a+b-c);
|
|
189
|
+
}
|
|
190
|
+
int ctx=0;
|
|
191
|
+
if(y>0&&x>0){
|
|
192
|
+
int d1=rec[(y-1)*w+x]-rec[(y-1)*w+x-1];
|
|
193
|
+
int d2=rec[(y-1)*w+x-1]-rec[y*w+x-1];
|
|
194
|
+
int d3=rec[y*w+x-1]-rec[(y-1)*w+x];
|
|
195
|
+
int act=((abs(d1)+abs(d2)+abs(d3))>8)?1:0;
|
|
196
|
+
ctx=(((q5(d1)+2)*5+(q5(d2)+2))*5+(q5(d3)+2))*2+act;
|
|
197
|
+
}
|
|
198
|
+
int base=ctx*NB, bt, kk=0, k=0;
|
|
199
|
+
for(int i=0;i<=12;i++){
|
|
200
|
+
int idx=base+(i<12?i:12);
|
|
201
|
+
dec_bin(&d,&low,&high,&value,N0,N1,idx,&bt);
|
|
202
|
+
if(bt==0){ kk=i; break; }
|
|
203
|
+
kk=i+1;
|
|
204
|
+
}
|
|
205
|
+
if(kk>12) kk=12;
|
|
206
|
+
int mag=0;
|
|
207
|
+
if(kk>1){
|
|
208
|
+
for(int i=kk-2;i>=0;i--){
|
|
209
|
+
int idx=base+18+(i<7?i:7);
|
|
210
|
+
dec_bin(&d,&low,&high,&value,N0,N1,idx,&bt);
|
|
211
|
+
mag=(mag<<1)|bt;
|
|
212
|
+
}
|
|
213
|
+
mag |= (1<<(kk-1));
|
|
214
|
+
} else if(kk==1) mag=1;
|
|
215
|
+
else mag=0;
|
|
216
|
+
int rq=mag;
|
|
217
|
+
if(kk>0||mag>0){
|
|
218
|
+
int idx=base+26;
|
|
219
|
+
dec_bin(&d,&low,&high,&value,N0,N1,idx,&bt);
|
|
220
|
+
if(bt==1) rq=-rq;
|
|
221
|
+
}
|
|
222
|
+
int rv=pred+rq*q; if(rv<0) rv=0; if(rv>255) rv=255;
|
|
223
|
+
rec[y*w+x]=(int16_t)rv;
|
|
224
|
+
rec_out[y*w+x]=(uint8_t)rv;
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
free(N0); free(N1); free(rec);
|
|
228
|
+
}
|
hansu/_yco.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Reversible YCoCg-R colour transform (integer, exact)."""
|
|
3
|
+
import numpy as np
|
|
4
|
+
|
|
5
|
+
def fwd(rgb):
|
|
6
|
+
R = rgb[..., 0].astype(np.int32); G = rgb[..., 1].astype(np.int32); B = rgb[..., 2].astype(np.int32)
|
|
7
|
+
Co = R - B; t = B + (Co >> 1); Cg = G - t; Y = t + (Cg >> 1)
|
|
8
|
+
return Y.astype(np.int64), Cg.astype(np.int64), Co.astype(np.int64)
|
|
9
|
+
|
|
10
|
+
def inv(Y, Cg, Co):
|
|
11
|
+
t = Y - (Cg >> 1); G = Cg + t; B = t - (Co >> 1); R = B + Co
|
|
12
|
+
return np.clip(np.stack([R, G, B], -1), 0, 255).astype(np.uint8)
|
hansu/build_c.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Build the optional C backend: python -m hansu.build_c"""
|
|
3
|
+
import os, subprocess, sys, shutil
|
|
4
|
+
|
|
5
|
+
def main():
|
|
6
|
+
here = os.path.dirname(os.path.abspath(__file__))
|
|
7
|
+
src = os.path.join(here, "_hs_ac.c")
|
|
8
|
+
out = os.path.join(here, "_hs_ac_c.so" if os.name != "nt" else "_hs_ac_c.dll")
|
|
9
|
+
cc = os.environ.get("CC") or shutil.which("gcc") or shutil.which("cc") or shutil.which("clang")
|
|
10
|
+
if not cc:
|
|
11
|
+
print("no C compiler found; the package stays on the pure-Python backend")
|
|
12
|
+
return 1
|
|
13
|
+
cmd = [cc, "-O3", "-shared", "-fPIC", "-o", out, src, "-lm"]
|
|
14
|
+
print(" ".join(cmd)); subprocess.check_call(cmd)
|
|
15
|
+
from . import _fast
|
|
16
|
+
print("C backend built:", _fast.available())
|
|
17
|
+
return 0
|
|
18
|
+
|
|
19
|
+
if __name__ == "__main__":
|
|
20
|
+
sys.exit(main())
|
hansu/cli.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
# -*- coding: utf-8 -*-
|
|
2
|
+
"""Command line: hansu sign/lib/query/encode/decode/bench/info."""
|
|
3
|
+
import argparse, json, os, sys, time
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
def _load(p):
|
|
7
|
+
from PIL import Image
|
|
8
|
+
im = np.array(Image.open(p))
|
|
9
|
+
return im if im.ndim == 3 else np.dstack([im, im, im])
|
|
10
|
+
|
|
11
|
+
def main(argv=None):
|
|
12
|
+
from . import codec, standalone, topology, index, _backend
|
|
13
|
+
ap = argparse.ArgumentParser(prog="hansu", description="HS2 image codec + topology signatures")
|
|
14
|
+
sp = ap.add_subparsers(dest="cmd", required=True)
|
|
15
|
+
|
|
16
|
+
s = sp.add_parser("sign", help="print or save topology signatures")
|
|
17
|
+
s.add_argument("files", nargs="+"); s.add_argument("-o", "--out-dir")
|
|
18
|
+
|
|
19
|
+
s = sp.add_parser("lib", help="build a signature library from a directory")
|
|
20
|
+
s.add_argument("dir"); s.add_argument("-o", "--out", default="hansu-library.json")
|
|
21
|
+
s.add_argument("-r", "--recursive", action="store_true")
|
|
22
|
+
|
|
23
|
+
s = sp.add_parser("query", help="find topology neighbours of an image")
|
|
24
|
+
s.add_argument("img"); s.add_argument("--lib", required=True); s.add_argument("-k", type=int, default=3)
|
|
25
|
+
|
|
26
|
+
s = sp.add_parser("encode", help="encode an image to .hs2")
|
|
27
|
+
s.add_argument("img"); s.add_argument("-o", "--out", required=True)
|
|
28
|
+
s.add_argument("--qy", type=int, default=16); s.add_argument("--qc", type=int, default=8)
|
|
29
|
+
s.add_argument("--banded", type=int); s.add_argument("--threads", type=int, default=0)
|
|
30
|
+
|
|
31
|
+
s = sp.add_parser("decode", help="decode .hs2 (standalone implementation)")
|
|
32
|
+
s.add_argument("inp"); s.add_argument("-o", "--out", required=True)
|
|
33
|
+
|
|
34
|
+
s = sp.add_parser("bench", help="encode a directory and report sizes")
|
|
35
|
+
s.add_argument("dir"); s.add_argument("--qy", type=int, default=16); s.add_argument("--qc", type=int, default=8)
|
|
36
|
+
|
|
37
|
+
s = sp.add_parser("info", help="show backend and format version")
|
|
38
|
+
a = ap.parse_args(argv)
|
|
39
|
+
|
|
40
|
+
if a.cmd == "info":
|
|
41
|
+
from . import _arith, _fast
|
|
42
|
+
print(f"hansu {__import__('hansu').__version__} format HS2 v{codec.VER}")
|
|
43
|
+
print(f"backend: {_backend.NAME} (C available: {_fast.available()})")
|
|
44
|
+
return 0
|
|
45
|
+
|
|
46
|
+
if a.cmd == "sign":
|
|
47
|
+
for p in a.files:
|
|
48
|
+
sig = topology.signature(_load(p))
|
|
49
|
+
if a.out_dir:
|
|
50
|
+
os.makedirs(a.out_dir, exist_ok=True)
|
|
51
|
+
out = os.path.join(a.out_dir, os.path.splitext(os.path.basename(p))[0] + ".json")
|
|
52
|
+
topology.save(sig, out); print(f"{p} -> {out}")
|
|
53
|
+
else:
|
|
54
|
+
print(json.dumps(sig, ensure_ascii=False, indent=2))
|
|
55
|
+
return 0
|
|
56
|
+
|
|
57
|
+
if a.cmd == "lib":
|
|
58
|
+
lib = index.build(a.dir, a.recursive); index.save(lib, a.out)
|
|
59
|
+
print(f"{a.out}: {len(lib)} entries"); return 0
|
|
60
|
+
|
|
61
|
+
if a.cmd == "query":
|
|
62
|
+
lib = index.load(a.lib); q = topology.signature(_load(a.img))
|
|
63
|
+
print(f"{a.img} family={q['family']} colors={q['colors']}")
|
|
64
|
+
for d, p in index.query(lib, q, a.k):
|
|
65
|
+
s = lib[p]
|
|
66
|
+
print(f" {d:.4f} {p} [{s['family']} {s['colors']} colours {s['codec']['bytes']} B]")
|
|
67
|
+
return 0
|
|
68
|
+
|
|
69
|
+
if a.cmd == "encode":
|
|
70
|
+
from PIL import Image
|
|
71
|
+
im = _load(a.img); t = time.time()
|
|
72
|
+
if a.banded:
|
|
73
|
+
data = codec.encode_banded(im, a.qy, a.qc, k=a.banded, threads=a.threads or None)
|
|
74
|
+
rec = codec.decode_banded(data)
|
|
75
|
+
else:
|
|
76
|
+
data, rec, route = codec.encode_auto(im, a.qy, a.qc, threads=a.threads or None)
|
|
77
|
+
ms = (time.time() - t) * 1000
|
|
78
|
+
open(a.out, "wb").write(data)
|
|
79
|
+
mse = float(np.mean((im[..., :3].astype(float) - rec[..., :3].astype(float)) ** 2))
|
|
80
|
+
psnr = 99.0 if mse < 1e-9 else 20 * np.log10(255 / np.sqrt(mse))
|
|
81
|
+
print(f"{a.img} -> {a.out} {len(data)} B {ms:.0f} ms PSNR {psnr:.2f} dB")
|
|
82
|
+
return 0
|
|
83
|
+
|
|
84
|
+
if a.cmd == "decode":
|
|
85
|
+
from PIL import Image
|
|
86
|
+
rec = standalone.decode(open(a.inp, "rb").read())
|
|
87
|
+
Image.fromarray(rec).save(a.out)
|
|
88
|
+
print(f"{a.inp} -> {a.out} {rec.shape}")
|
|
89
|
+
return 0
|
|
90
|
+
|
|
91
|
+
if a.cmd == "bench":
|
|
92
|
+
tot = 0; rows = []
|
|
93
|
+
for fn in sorted(os.listdir(a.dir)):
|
|
94
|
+
if not fn.lower().endswith((".png", ".jpg", ".jpeg", ".bmp", ".webp")): continue
|
|
95
|
+
p = os.path.join(a.dir, fn); im = _load(p); t = time.time()
|
|
96
|
+
data, rec, route = codec.encode_auto(im, a.qy, a.qc, threads=4)
|
|
97
|
+
rows.append((fn, im.shape, len(data), (time.time() - t) * 1000, route)); tot += len(data)
|
|
98
|
+
print(f"{'file':<28}{'shape':>14}{'bytes':>10}{'ms':>8} route")
|
|
99
|
+
for r in rows: print(f"{r[0]:<28}{str(r[1]):>14}{r[2]:>10}{r[3]:>8.0f} {r[4]}")
|
|
100
|
+
print(f"{len(rows)} images, {tot} B total")
|
|
101
|
+
return 0
|
|
102
|
+
return 1
|