or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/pypi-pyzbar

Read one-dimensional barcodes and QR codes from Python 2 and 3.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyzbar@0.1.x

To install, run

npx @tessl/cli install tessl/pypi-pyzbar@0.1.0

0

# PyZbar

1

2

A pure Python library for reading one-dimensional barcodes and QR codes. PyZbar provides a simple, efficient interface to decode barcodes from various image sources including PIL/Pillow images, OpenCV/imageio/numpy arrays, and raw bytes. It returns detailed information about decoded symbols including the data, barcode type, bounding boxes, and exact polygon coordinates.

3

4

## Package Information

5

6

- **Package Name**: pyzbar

7

- **Language**: Python

8

- **Installation**: `pip install pyzbar`

9

- **System Dependencies**: `zbar` library (included with Windows wheels, requires separate installation on Linux/macOS)

10

11

## Core Imports

12

13

```python

14

from pyzbar.pyzbar import decode

15

```

16

17

Import supporting data types:

18

19

```python

20

from pyzbar.pyzbar import decode, Decoded, Point, Rect, ZBarSymbol

21

```

22

23

## Basic Usage

24

25

```python

26

from pyzbar.pyzbar import decode

27

from PIL import Image

28

29

# Decode from PIL Image

30

image = Image.open("barcode.png")

31

decoded_objects = decode(image)

32

33

for obj in decoded_objects:

34

print(f"Data: {obj.data.decode('utf-8')}")

35

print(f"Type: {obj.type}")

36

print(f"Rect: {obj.rect}")

37

print(f"Polygon: {obj.polygon}")

38

39

# Decode from OpenCV/numpy array

40

import cv2

41

image = cv2.imread("qrcode.png")

42

decoded_objects = decode(image)

43

44

# Decode from raw bytes

45

with open("barcode.png", "rb") as f:

46

image_data = f.read()

47

# Convert to pixel data format: (pixels, width, height)

48

# This example assumes you have the pixel data

49

decoded_objects = decode((pixels, width, height))

50

```

51

52

## Capabilities

53

54

### Barcode Decoding

55

56

Decodes various barcode and QR code formats from image data, returning detailed information about each symbol found including location coordinates and metadata.

57

58

```python { .api }

59

def decode(image, symbols=None):

60

"""

61

Decodes barcodes and QR codes from image data.

62

63

Args:

64

image: PIL.Image, numpy.ndarray, or tuple (pixels, width, height)

65

- PIL.Image: Must be in grayscale ('L' mode) or will be converted

66

- numpy.ndarray: 2D or 3D array (3D uses first channel only)

67

- tuple: (pixel_bytes, width, height) with 8-bit grayscale pixels

68

symbols: iterable of ZBarSymbol constants, optional

69

Specific barcode types to decode. If None (default), decodes all types.

70

71

Returns:

72

list: List of Decoded objects containing barcode information

73

"""

74

```

75

76

### Symbol Type Constants

77

78

Constants representing different barcode and QR code symbol types for selective decoding.

79

80

```python { .api }

81

class ZBarSymbol(IntEnum):

82

"""Enumeration of supported barcode symbol types."""

83

NONE = 0 # No symbol decoded

84

PARTIAL = 1 # Intermediate status

85

EAN2 = 2 # GS1 2-digit add-on

86

EAN5 = 5 # GS1 5-digit add-on

87

EAN8 = 8 # EAN-8

88

UPCE = 9 # UPC-E

89

ISBN10 = 10 # ISBN-10 (from EAN-13)

90

UPCA = 12 # UPC-A

91

EAN13 = 13 # EAN-13

92

ISBN13 = 14 # ISBN-13 (from EAN-13)

93

COMPOSITE = 15 # EAN/UPC composite

94

I25 = 25 # Interleaved 2 of 5

95

DATABAR = 34 # GS1 DataBar (RSS)

96

DATABAR_EXP = 35 # GS1 DataBar Expanded

97

CODABAR = 38 # Codabar

98

CODE39 = 39 # Code 39

99

PDF417 = 57 # PDF417

100

QRCODE = 64 # QR Code

101

SQCODE = 80 # SQ Code

102

CODE93 = 93 # Code 93

103

CODE128 = 128 # Code 128

104

```

105

106

### Geometry Utilities

107

108

Functions for computing bounding boxes and convex hulls from coordinate points, useful for analyzing barcode locations and creating custom processing workflows.

109

110

```python { .api }

111

def bounding_box(locations):

112

"""

113

Computes the bounding box of coordinate points.

114

115

Args:

116

locations: iterable of (x, y) coordinate tuples

117

118

Returns:

119

Rect: Bounding box coordinates

120

"""

121

122

def convex_hull(points):

123

"""

124

Computes the convex hull using Andrew's monotone chain algorithm.

125

126

Args:

127

points: iterable of (x, y) coordinate tuples

128

129

Returns:

130

list: List of Point objects forming the convex hull in counter-clockwise order

131

"""

132

```

133

134

### Library Dependencies

135

136

Information about loaded external dependencies, useful for application deployment and freezing.

137

138

```python { .api }

139

EXTERNAL_DEPENDENCIES = [] # List of loaded ctypes.CDLL objects

140

141

ORIENTATION_AVAILABLE = bool # Whether orientation detection is available

142

```

143

144

## Types

145

146

```python { .api }

147

class Decoded:

148

"""

149

Named tuple containing decoded barcode information.

150

151

Attributes:

152

data (bytes): The decoded barcode data

153

type (str): Barcode type name (e.g., 'CODE128', 'QRCODE')

154

rect (Rect): Bounding rectangle coordinates

155

polygon (list): List of (x, y) tuples defining symbol boundary

156

quality (int): Quality score of the decode (higher is better)

157

orientation (str or None): Symbol orientation ('UP', 'RIGHT', 'DOWN', 'LEFT') if available

158

"""

159

160

class Point:

161

"""

162

Named tuple representing a 2D coordinate point.

163

164

Attributes:

165

x (int): X coordinate

166

y (int): Y coordinate

167

"""

168

169

class Rect:

170

"""

171

Named tuple representing a rectangular bounding box.

172

173

Attributes:

174

left (int): Left edge X coordinate

175

top (int): Top edge Y coordinate

176

width (int): Width of rectangle

177

height (int): Height of rectangle

178

"""

179

180

class PyZbarError(Exception):

181

"""Exception raised when zbar operations fail."""

182

```

183

184

## Usage Examples

185

186

### Selective Symbol Type Decoding

187

188

```python

189

from pyzbar.pyzbar import decode, ZBarSymbol

190

from PIL import Image

191

192

# Decode only QR codes and Code 128 barcodes

193

image = Image.open("mixed_codes.png")

194

qr_and_code128 = decode(image, symbols=[ZBarSymbol.QRCODE, ZBarSymbol.CODE128])

195

196

# Decode only QR codes

197

qr_only = decode(image, symbols=[ZBarSymbol.QRCODE])

198

```

199

200

### Working with OpenCV and NumPy

201

202

```python

203

import cv2

204

import numpy as np

205

from pyzbar.pyzbar import decode

206

207

# Load image with OpenCV

208

image = cv2.imread("barcode.png")

209

210

# Convert BGR to grayscale if needed (decode handles this automatically)

211

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

212

213

# Decode barcodes

214

decoded_objects = decode(gray)

215

216

for obj in decoded_objects:

217

# Get barcode corners for drawing

218

points = np.array(obj.polygon, np.int32)

219

points = points.reshape((-1, 1, 2))

220

221

# Draw polygon around barcode

222

cv2.polylines(image, [points], True, (0, 255, 0), 2)

223

224

# Add text with barcode data

225

x, y = obj.rect.left, obj.rect.top

226

cv2.putText(image, obj.data.decode('utf-8'), (x, y-10),

227

cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

228

229

cv2.imshow("Decoded Barcodes", image)

230

cv2.waitKey(0)

231

```

232

233

### Error Handling

234

235

```python

236

from pyzbar.pyzbar import decode, PyZbarError

237

from PIL import Image

238

239

try:

240

image = Image.open("barcode.png")

241

decoded_objects = decode(image)

242

243

if not decoded_objects:

244

print("No barcodes found in image")

245

else:

246

for obj in decoded_objects:

247

print(f"Found {obj.type}: {obj.data.decode('utf-8')}")

248

249

except PyZbarError as e:

250

print(f"Error decoding barcode: {e}")

251

except Exception as e:

252

print(f"General error: {e}")

253

```

254

255

### Working with Raw Image Data

256

257

```python

258

from pyzbar.pyzbar import decode

259

260

# Example: decode from raw grayscale pixels

261

def decode_from_raw_data(pixel_bytes, width, height):

262

"""Decode barcodes from raw 8-bit grayscale pixel data."""

263

264

# Verify data length matches dimensions

265

expected_length = width * height

266

if len(pixel_bytes) != expected_length:

267

raise ValueError(f"Data length {len(pixel_bytes)} doesn't match dimensions {width}x{height}")

268

269

# Decode using tuple format

270

decoded_objects = decode((pixel_bytes, width, height))

271

return decoded_objects

272

273

# Usage with hypothetical raw data

274

width, height = 640, 480

275

pixel_data = b'\\x00' * (width * height) # Example grayscale data

276

results = decode_from_raw_data(pixel_data, width, height)

277

```

278

279

## Installation Notes

280

281

### System Dependencies

282

283

**Linux (Ubuntu/Debian):**

284

```bash

285

sudo apt-get install libzbar0

286

pip install pyzbar

287

```

288

289

**Linux (CentOS/RHEL):**

290

```bash

291

sudo yum install zbar

292

pip install pyzbar

293

```

294

295

**macOS:**

296

```bash

297

brew install zbar

298

pip install pyzbar

299

```

300

301

**Windows:**

302

Windows wheels include the zbar DLLs, no additional installation required:

303

```bash

304

pip install pyzbar

305

```

306

307

### Optional Dependencies

308

309

For the command-line script functionality:

310

```bash

311

pip install pyzbar[scripts] # Includes Pillow for image loading

312

```

313

314

## Command Line Usage

315

316

PyZbar includes a command-line script for quick barcode reading:

317

318

```bash

319

# Install with script dependencies

320

pip install pyzbar[scripts]

321

322

# Read barcodes from image files

323

read_zbar image1.png image2.jpg

324

325

# Display version

326

read_zbar --version

327

```

328

329

The script outputs the decoded data from each barcode found in the specified images.