File size: 3,679 Bytes
5a5e72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations

import struct
import zlib

import numpy as np

IMAGE_SIZE = 224
_PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"


class EvidenceError(ValueError):
    pass


def _chunk(kind: bytes, data: bytes) -> bytes:
    return (
        struct.pack(">I", len(data))
        + kind
        + data
        + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
    )


def encode_png_rgb(image: np.ndarray) -> bytes:
    array = np.asarray(image)
    if array.dtype != np.uint8 or array.ndim != 3 or array.shape[2] != 3 or 0 in array.shape[:2]:
        raise EvidenceError("PNG encoder accepts uint8 RGB HWC only")
    height, width = array.shape[:2]
    scanlines = np.zeros((height, 1 + width * 3), dtype=np.uint8)
    scanlines[:, 1:] = np.ascontiguousarray(array).reshape(height, width * 3)
    header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
    return (
        _PNG_SIGNATURE
        + _chunk(b"IHDR", header)
        + _chunk(b"IDAT", zlib.compress(scanlines.tobytes(), 9))
        + _chunk(b"IEND", b"")
    )


def decode_png_rgb(raw: bytes) -> np.ndarray:
    if not raw.startswith(_PNG_SIGNATURE):
        raise EvidenceError("PNG signature missing")
    idat: list[bytes]
    offset, header, idat, ended = len(_PNG_SIGNATURE), None, [], False
    while offset < len(raw):
        if offset + 8 > len(raw):
            raise EvidenceError("PNG chunk header truncated")
        (length,) = struct.unpack(">I", raw[offset : offset + 4])
        kind = raw[offset + 4 : offset + 8]
        data = raw[offset + 8 : offset + 8 + length]
        crc = raw[offset + 8 + length : offset + 12 + length]
        if (
            len(data) != length
            or len(crc) != 4
            or struct.unpack(">I", crc)[0] != (zlib.crc32(kind + data) & 0xFFFFFFFF)
        ):
            raise EvidenceError("PNG chunk is truncated or fails its CRC")
        offset += 12 + length
        if kind == b"IHDR" and header is None and length == 13:
            header = struct.unpack(">IIBBBBB", data)
        elif kind == b"IDAT" and header is not None:
            idat.append(data)
        elif kind == b"IEND" and length == 0:
            ended = True
            break
        else:
            raise EvidenceError("Unexpected PNG chunk")
    if not ended or offset != len(raw) or header is None:
        raise EvidenceError("PNG stream is incomplete or has trailing bytes")
    width, height, depth, color, compression, filtering, interlace = header
    if (
        (depth, color, compression, filtering, interlace) != (8, 2, 0, 0, 0)
        or not width
        or not height
    ):
        raise EvidenceError("Only non-interlaced 8-bit RGB PNG is accepted")
    data = zlib.decompress(b"".join(idat))
    stride = 1 + width * 3
    if len(data) != stride * height:
        raise EvidenceError("PNG pixel payload size mismatch")
    rows = np.frombuffer(data, dtype=np.uint8).reshape(height, stride)
    if np.any(rows[:, 0] != 0):
        raise EvidenceError("Only PNG filter type 0 is accepted")
    return rows[:, 1:].reshape(height, width, 3).copy()


def quantize_rgb(chw: np.ndarray) -> tuple[np.ndarray, float]:
    array = np.asarray(chw)
    if array.dtype != np.float32 or array.shape != (3, IMAGE_SIZE, IMAGE_SIZE):
        raise EvidenceError("Image must be float32 CHW (3,224,224)")
    if not np.isfinite(array).all():
        raise EvidenceError("Image contains non-finite values")
    outside = int(np.count_nonzero((array < 0.0) | (array > 1.0)))
    quantized = np.rint(np.clip(array.astype(np.float64), 0.0, 1.0) * 255.0).astype(np.uint8)
    return np.ascontiguousarray(quantized.transpose(1, 2, 0)), outside / array.size