I'll help create Python encoder/decoder functions for this iRGB image format. Let's break it down and implement both functions.
import struct
from typing import List, Tuple, BinaryIO
from dataclasses import dataclass
import numpy as np
@dataclass
class RGBColor:
r: int
g: int
b: int
@dataclass
class ImageHeader:
width: int
height: int
@dataclass
class IRGBImage:
header: ImageHeader
palette: List[RGBColor]
pixel_data: np.ndarray # 2D array of indices (0-15)
def decode_irgb(file_path: str) -> IRGBImage:
with open(file_path, 'rb') as f:
# Read header
width, height = struct.unpack('<HH', f.read(4))
header = ImageHeader(width, height)
# Read palette
palette = []
for _ in range(16):
r, g, b = struct.unpack('BBB', f.read(3))
palette.append(RGBColor(r, g, b))
# Read RLE-encoded pixel data
pixels = np.zeros((height, width), dtype=np.uint8)
pixel_idx = 0
while pixel_idx < width * height:
ctrl = struct.unpack('<B', f.read(1))[0]
if ctrl & 0x80: # Run packet
run_length = ctrl & 0x7F
val = struct.unpack('<B', f.read(1))[0] >> 4
for _ in range(run_length):
pixels[pixel_idx // width, pixel_idx % width] = val
pixel_idx += 1
else: # Literal packet
lit_length = ctrl
bytes_to_read = (lit_length + 1) // 2
data = f.read(bytes_to_read)
for i in range(lit_length):
if i % 2 == 0:
val = data[i // 2] >> 4
else:
val = data[i // 2] & 0x0F
pixels[pixel_idx // width, pixel_idx % width] = val
pixel_idx += 1
# Handle alignment
if bytes_to_read % 2:
f.read(1) # Skip padding byte
return IRGBImage(header, palette, pixels)
def encode_irgb(image: IRGBImage, file_path: str):
with open(file_path, 'wb') as f:
# Write header
f.write(struct.pack('<HH', image.header.width, image.header.height))
# Write palette
for color in image.palette:
f.write(struct.pack('BBB', color.r, color.g, color.b))
# Encode pixel data with RLE
pixels = image.pixel_data.flatten()
i = 0
while i < len(pixels):
# Look ahead for run
run_length = 1
while (i + run_length < len(pixels) and
pixels[i + run_length] == pixels[i] and
run_length < 127):
run_length += 1
if run_length > 2: # Use run packet
ctrl = 0x80 | run_length
val = pixels[i] << 4
f.write(struct.pack('<BB', ctrl, val))
i += run_length
else: # Use literal packet
# Count literals
lit_start = i
lit_length = 0
while (lit_length < 127 and
i + lit_length < len(pixels) and
(i + lit_length + 1 >= len(pixels) or
pixels[i + lit_length] != pixels[i + lit_length + 1] or
lit_length < 2)):
lit_length += 1
f.write(struct.pack('<B', lit_length))
# Pack nibbles
for j in range(0, lit_length, 2):
if j + 1 < lit_length:
packed = (pixels[i + j] << 4) | pixels[i + j + 1]
else:
packed = pixels[i + j] << 4
f.write(struct.pack('<B', packed))
# Add padding if needed
if (lit_length + 1) // 2 % 2:
f.write(b'\x00')
i += lit_length
# Example usage:
def create_test_image() -> IRGBImage:
header = ImageHeader(width=16, height=16)
palette = [RGBColor(r=(i*16), g=(i*16), b=(i*16)) for i in range(16)]
pixels = np.zeros((16, 16), dtype=np.uint8)
# Create a test pattern
for y in range(16):
for x in range(16):
pixels[y, x] = (x + y) % 16
return IRGBImage(header, palette, pixels)
if __name__ == "__main__":
# Create and save test image
test_image = create_test_image()
encode_irgb(test_image, "test.irgb")
# Read it back
decoded_image = decode_irgb("test.irgb")
# Verify
assert np.array_equal(test_image.pixel_data, decoded_image.pixel_data)
print("Encoding/decoding test passed!")
This implementation includes:
- Data structures for representing the image format
- A decoder that reads the binary format and creates an IRGBImage object
- An encoder that takes an IRGBImage object and writes it to a file
- RLE compression/decompression following the specified format
- Proper handling of the 4bpp format and palette
- Alignment requirements as specified
- A test function to verify the implementation
Key features of the implementation:
- Uses little-endian encoding as specified
- Handles both run-length and literal packets
- Maintains 2-byte alignment for the pixel stream
- Properly packs/unpacks 4-bit values
- Includes type hints for better code clarity
- Uses numpy for efficient pixel data handling
To use this code, you can either:
- Create an IRGBImage object and encode it to a file
- Read an existing iRGB file and decode it to an IRGBImage object
The test code demonstrates both operations and verifies that the encoding/decoding process is lossless.
Would you like me to explain any particular part in more detail or add any additional features?