or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-processing.mdcolor-management.mdimage-formats.mdimage-io.mdindex.mdlossless-compression.mdscientific-compression.mdutilities.md

image-io.mddocs/

0

# Image I/O Functions

1

2

High-level functions for reading and writing image files with automatic codec detection, format conversion, and memory-efficient processing. These functions provide a convenient interface for working with various image formats without needing to know the specific codec details.

3

4

## Capabilities

5

6

### Reading Images

7

8

Read image data from files or byte streams with automatic format detection and codec selection.

9

10

```python { .api }

11

def imread(fileobj, /, codec=None, *, memmap=True, return_codec=False, **kwargs):

12

"""

13

Return image array from file.

14

15

Parameters:

16

- fileobj: str | os.PathLike[Any] | bytes | mmap.mmap - File path, file-like object, or bytes data

17

- codec: str | Callable[..., NDArray[Any]] | list[str | Callable[..., NDArray[Any]]] | None -

18

Codec name(s) or decoder function(s) to try. If None, auto-detect from file extension/content

19

- memmap: bool - Use memory mapping for large files (default True)

20

- return_codec: bool - If True, return (array, codec_function) tuple (default False)

21

- **kwargs: Additional codec-specific parameters passed to decoder

22

23

Returns:

24

NDArray[Any] | tuple[NDArray[Any], Callable[..., NDArray[Any]]]: Image array or (array, codec) tuple

25

26

Raises:

27

FileNotFoundError: If file path does not exist

28

DelayedImportError: If required codec is not available

29

Various codec-specific exceptions: For decoding errors

30

"""

31

```

32

33

**Usage Examples:**

34

35

```python

36

import imagecodecs

37

import numpy as np

38

39

# Basic image reading

40

image = imagecodecs.imread('photo.jpg')

41

print(f"Image shape: {image.shape}, dtype: {image.dtype}")

42

43

# Read with specific codec

44

image = imagecodecs.imread('data.tiff', codec='tiff')

45

46

# Try multiple codecs in order

47

image = imagecodecs.imread('unknown.bin', codec=['tiff', 'png', 'jpeg'])

48

49

# Memory-mapped reading for large files

50

large_image = imagecodecs.imread('huge_image.tiff', memmap=True)

51

52

# Get codec information

53

image, codec_func = imagecodecs.imread('photo.jpg', return_codec=True)

54

print(f"Used codec: {codec_func.__name__}")

55

56

# Codec-specific parameters

57

jpeg_image = imagecodecs.imread('photo.jpg', colorspace='rgb')

58

tiff_image = imagecodecs.imread('data.tiff', key=0) # Read specific TIFF page

59

```

60

61

### Writing Images

62

63

Write image arrays to files with automatic format selection based on file extension or explicit codec specification.

64

65

```python { .api }

66

def imwrite(fileobj, data, /, codec=None, **kwargs):

67

"""

68

Write image array to file.

69

70

Parameters:

71

- fileobj: str | os.PathLike[Any] | IO[bytes] - Output file path

72

- data: ArrayLike - Image data to write (2D or 3D array)

73

- codec: str | Callable[..., bytes | bytearray] | None - Codec name or encoder function. If None, auto-detect from file extension

74

- **kwargs: Additional codec-specific parameters passed to encoder

75

76

Returns:

77

None

78

79

Raises:

80

ValueError: If data format is incompatible with chosen codec

81

DelayedImportError: If required codec is not available

82

Various codec-specific exceptions: For encoding errors

83

"""

84

```

85

86

**Usage Examples:**

87

88

```python

89

import imagecodecs

90

import numpy as np

91

92

# Create sample image data

93

image = np.random.randint(0, 256, (512, 512, 3), dtype=np.uint8)

94

95

# Basic image writing (codec auto-detected from extension)

96

imagecodecs.imwrite('output.png', image)

97

imagecodecs.imwrite('output.jpg', image)

98

imagecodecs.imwrite('output.tiff', image)

99

100

# Write with specific codec

101

imagecodecs.imwrite('output.bin', image, codec='png')

102

103

# Codec-specific parameters

104

imagecodecs.imwrite('high_quality.jpg', image, level=95, optimize=True)

105

imagecodecs.imwrite('compressed.png', image, level=9)

106

imagecodecs.imwrite('lossless.webp', image, lossless=True)

107

108

# Multi-page TIFF

109

pages = [np.random.randint(0, 256, (256, 256), dtype=np.uint8) for _ in range(5)]

110

for i, page in enumerate(pages):

111

imagecodecs.imwrite('multipage.tiff', page, append=i > 0)

112

```

113

114

### File Extension Support

115

116

Get information about supported file formats and extensions.

117

118

```python { .api }

119

def imagefileext():

120

"""

121

Return list of image file extensions handled by imread/imwrite.

122

123

Returns:

124

list[str]: List of supported file extensions (without leading dot)

125

"""

126

```

127

128

**Usage Examples:**

129

130

```python

131

import imagecodecs

132

133

# Get all supported extensions

134

extensions = imagecodecs.imagefileext()

135

print(f"Supported formats: {len(extensions)}")

136

print(f"Extensions: {extensions}")

137

138

# Check if specific format is supported

139

if 'webp' in extensions:

140

print("WebP format is supported")

141

142

# Filter files by supported extensions

143

import os

144

supported_files = []

145

for filename in os.listdir('.'):

146

ext = filename.split('.')[-1].lower()

147

if ext in extensions:

148

supported_files.append(filename)

149

```

150

151

## Supported Image Formats

152

153

The imread/imwrite functions support numerous image formats through their respective codecs:

154

155

### Common Formats

156

- **JPEG** (.jpg, .jpeg) - Lossy compression for photographs

157

- **PNG** (.png) - Lossless compression with transparency support

158

- **TIFF** (.tiff, .tif) - Flexible format supporting multiple pages and data types

159

- **BMP** (.bmp) - Uncompressed bitmap format

160

- **GIF** (.gif) - Palette-based format with animation support

161

162

### Next-Generation Formats

163

- **WebP** (.webp) - Modern format with superior compression

164

- **AVIF** (.avif) - AV1-based format with excellent compression

165

- **HEIF** (.heif, .heic) - High efficiency format used by Apple devices

166

- **JPEG XL** (.jxl) - Next-generation JPEG replacement

167

168

### Scientific Formats

169

- **JPEG 2000** (.jp2, .j2k) - Wavelet-based compression for medical imaging

170

- **JPEG XS** (.jxs) - Low-latency format for professional video

171

- **JPEG-LS** (.jls) - Lossless/near-lossless compression

172

173

### Specialized Formats

174

- **QOI** (.qoi) - Simple lossless format

175

- **RGBE** (.hdr) - High dynamic range format

176

- **EER** (.eer) - Electron microscopy format

177

178

## Data Type Support

179

180

### Input Data Types

181

- **uint8**: Standard 8-bit images (0-255)

182

- **uint16**: 16-bit images (0-65535)

183

- **float32/float64**: Floating-point images (typically 0.0-1.0)

184

- **int8/int16/int32**: Signed integer formats

185

186

### Array Shapes

187

- **2D arrays**: Grayscale images (height, width)

188

- **3D arrays**: Color images (height, width, channels)

189

- RGB: 3 channels

190

- RGBA: 4 channels (with alpha)

191

- CMYK: 4 channels (for printing)

192

193

### Memory Layout

194

- **C-contiguous**: Default NumPy layout (row-major)

195

- **Fortran-contiguous**: Column-major layout (supported by most codecs)

196

- **Memory-mapped**: For processing large files without loading into RAM

197

198

## Error Handling

199

200

```python { .api }

201

class DelayedImportError(ImportError):

202

"""Raised when a required codec library is not available."""

203

204

def __init__(self, name: str) -> None: ...

205

206

# Codec-specific exceptions inherit from their respective base classes

207

class JpegError(Exception): ...

208

class PngError(Exception): ...

209

class TiffError(Exception): ...

210

# ... additional codec exceptions

211

```

212

213

Common error scenarios:

214

215

```python

216

import imagecodecs

217

218

try:

219

image = imagecodecs.imread('corrupted.jpg')

220

except imagecodecs.JpegError as e:

221

print(f"JPEG decoding failed: {e}")

222

except imagecodecs.DelayedImportError as e:

223

print(f"Required library not available: {e}")

224

except FileNotFoundError:

225

print("File not found")

226

227

try:

228

imagecodecs.imwrite('output.webp', image)

229

except imagecodecs.DelayedImportError:

230

print("WebP codec not available, falling back to PNG")

231

imagecodecs.imwrite('output.png', image)

232

```

233

234

## Performance Considerations

235

236

### Memory Usage

237

- Use `memmap=True` for large files to avoid loading entire image into memory

238

- Specify output buffer with `out` parameter to reduce memory allocations

239

- Choose appropriate data types (uint8 vs float32) based on precision needs

240

241

### Codec Selection

242

- JPEG: Best for photographs and natural images

243

- PNG: Best for screenshots, graphics, and images requiring lossless compression

244

- WebP/AVIF: Modern formats with superior compression ratios

245

- TIFF: Best for scientific data and multi-page documents

246

247

### Multi-threading

248

Some codecs support parallel processing:

249

250

```python

251

# Multi-threaded JPEG decoding (when available)

252

image = imagecodecs.imread('large.jpg', numthreads=4)

253

254

# Multi-threaded encoding

255

imagecodecs.imwrite('output.avif', image, numthreads=8)

256

```