or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

aruco.mdcamera-calibration.mdcomputational-photography.mdcontours-shapes.mdcore-operations.mddnn.mdfeature-detection.mdgui-drawing.mdimage-processing.mdimage-video-io.mdindex.mdmachine-learning.mdobject-detection.mdtask-log.mdvideo-analysis.md

image-video-io.mddocs/

0

# Image and Video I/O

1

2

OpenCV provides comprehensive functionality for reading and writing images and videos through its `imgcodecs` and `videoio` modules. All functions and classes are accessible directly from the `cv2` namespace, supporting a wide variety of image formats (JPEG, PNG, TIFF, BMP, etc.) and video codecs.

3

4

## Capabilities

5

6

### Image Reading

7

8

Read images from files using various formats and loading modes.

9

10

```python { .api }

11

cv2.imread(filename: str, flags: int = cv2.IMREAD_COLOR) -> np.ndarray | None

12

```

13

14

Loads an image from the specified file.

15

16

**Parameters:**

17

- `filename` (str): Path to the image file

18

- `flags` (int, optional): Read mode flag. Defaults to `cv2.IMREAD_COLOR`

19

- `cv2.IMREAD_COLOR` - Load as 3-channel BGR color image (default)

20

- `cv2.IMREAD_GRAYSCALE` - Load as single-channel grayscale image

21

- `cv2.IMREAD_UNCHANGED` - Load image with alpha channel if present

22

- `cv2.IMREAD_ANYDEPTH` - Load 16-bit or 32-bit image when available

23

- `cv2.IMREAD_ANYCOLOR` - Load in any color format available

24

- `cv2.IMREAD_REDUCED_GRAYSCALE_2` - Load as grayscale at 1/2 size

25

- `cv2.IMREAD_REDUCED_GRAYSCALE_4` - Load as grayscale at 1/4 size

26

- `cv2.IMREAD_REDUCED_GRAYSCALE_8` - Load as grayscale at 1/8 size

27

- `cv2.IMREAD_REDUCED_COLOR_2` - Load as color at 1/2 size

28

- `cv2.IMREAD_REDUCED_COLOR_4` - Load as color at 1/4 size

29

- `cv2.IMREAD_REDUCED_COLOR_8` - Load as color at 1/8 size

30

31

**Returns:**

32

- `np.ndarray | None`: Image as NumPy array in BGR format, or `None` if reading failed

33

34

**Example:**

35

```python

36

import cv2

37

38

# Read color image

39

img = cv2.imread('photo.jpg')

40

41

# Read as grayscale

42

gray = cv2.imread('photo.jpg', cv2.IMREAD_GRAYSCALE)

43

44

# Read with alpha channel

45

rgba = cv2.imread('logo.png', cv2.IMREAD_UNCHANGED)

46

47

# Read at reduced resolution

48

small = cv2.imread('large.jpg', cv2.IMREAD_REDUCED_COLOR_2)

49

```

50

51

---

52

53

```python { .api }

54

cv2.imdecode(buf: np.ndarray, flags: int) -> np.ndarray | None

55

```

56

57

Decodes an image from a memory buffer.

58

59

**Parameters:**

60

- `buf` (np.ndarray): Input byte array containing encoded image data

61

- `flags` (int): Read mode flag (same as `cv2.imread()`)

62

63

**Returns:**

64

- `np.ndarray | None`: Decoded image as NumPy array, or `None` if decoding failed

65

66

**Example:**

67

```python

68

import cv2

69

import numpy as np

70

71

# Read image file as bytes

72

with open('image.jpg', 'rb') as f:

73

img_bytes = f.read()

74

75

# Decode from bytes

76

buf = np.frombuffer(img_bytes, dtype=np.uint8)

77

img = cv2.imdecode(buf, cv2.IMREAD_COLOR)

78

```

79

80

---

81

82

```python { .api }

83

cv2.imreadmulti(filename: str, mats: list, flags: int = cv2.IMREAD_ANYCOLOR) -> tuple[bool, list]

84

```

85

86

Loads a multi-page image from a file.

87

88

**Parameters:**

89

- `filename` (str): Name of file to be loaded

90

- `mats` (list): Output vector of Mat objects holding each page

91

- `flags` (int, optional): Flag that can take values of ImreadModes. Defaults to `cv2.IMREAD_ANYCOLOR`

92

93

**Returns:**

94

- `tuple[bool, list]`: Tuple of (success flag, list of images). Returns `True` if successful, `False` otherwise. Useful for reading multi-page TIFF files or animated image formats

95

96

**Example:**

97

```python

98

import cv2

99

100

# Read multi-page TIFF

101

success, images = cv2.imreadmulti('multipage.tiff', [], cv2.IMREAD_ANYCOLOR)

102

if success:

103

print(f'Read {len(images)} pages')

104

for i, img in enumerate(images):

105

cv2.imshow(f'Page {i}', img)

106

```

107

108

**Alternative with range:**

109

```python { .api }

110

cv2.imreadmulti(filename: str, mats: list, start: int, count: int, flags: int = cv2.IMREAD_ANYCOLOR) -> tuple[bool, list]

111

```

112

113

Loads images of a multi-page image from a file with specified range.

114

115

**Parameters:**

116

- `filename` (str): Name of file to be loaded

117

- `mats` (list): Output vector of Mat objects holding each page

118

- `start` (int): Start index of the image to load

119

- `count` (int): Count number of images to load

120

- `flags` (int, optional): Flag that can take values of ImreadModes

121

122

**Returns:**

123

- `tuple[bool, list]`: Tuple of (success flag, list of images)

124

125

---

126

127

```python { .api }

128

cv2.imcount(filename: str, flags: int = cv2.IMREAD_ANYCOLOR) -> int

129

```

130

131

Returns the number of images inside the given file.

132

133

**Parameters:**

134

- `filename` (str): Name of file to be loaded

135

- `flags` (int, optional): Flag that can take values of ImreadModes. Defaults to `cv2.IMREAD_ANYCOLOR`

136

137

**Returns:**

138

- `int`: Number of images/pages/frames in the file. Returns the number of pages in a multi-page image (e.g. TIFF), the number of frames in an animation (e.g. AVIF), and 1 otherwise. If the image cannot be decoded, 0 is returned

139

140

**Example:**

141

```python

142

import cv2

143

144

# Check number of pages in TIFF file

145

num_pages = cv2.imcount('multipage.tiff')

146

print(f'File contains {num_pages} pages')

147

148

# Read only if multiple pages exist

149

if num_pages > 1:

150

success, images = cv2.imreadmulti('multipage.tiff', [])

151

```

152

153

---

154

155

```python { .api }

156

cv2.haveImageReader(filename: str) -> bool

157

```

158

159

Checks if an image reader for the specified format is available.

160

161

**Parameters:**

162

- `filename` (str): File path or filename with extension

163

164

**Returns:**

165

- `bool`: `True` if reader is available, `False` otherwise

166

167

**Example:**

168

```python

169

if cv2.haveImageReader('test.webp'):

170

img = cv2.imread('test.webp')

171

```

172

173

### Image Writing

174

175

Write images to files with format-specific parameters.

176

177

```python { .api }

178

cv2.imwrite(filename: str, img: np.ndarray, params: list[int] = None) -> bool

179

```

180

181

Saves an image to a file. The format is determined by the file extension.

182

183

**Parameters:**

184

- `filename` (str): Path to save the image file

185

- `img` (np.ndarray): Image array to save

186

- `params` (list[int], optional): Format-specific parameters as list of (flag, value) pairs

187

- `cv2.IMWRITE_JPEG_QUALITY` - JPEG quality (0-100, default 95)

188

- `cv2.IMWRITE_PNG_COMPRESSION` - PNG compression level (0-9, default 3)

189

- Additional codec-specific parameters available

190

191

**Returns:**

192

- `bool`: `True` if successful, `False` otherwise

193

194

**Example:**

195

```python

196

import cv2

197

198

img = cv2.imread('input.png')

199

200

# Save as JPEG with quality 90

201

cv2.imwrite('output.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 90])

202

203

# Save as PNG with maximum compression

204

cv2.imwrite('output.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])

205

206

# Save with default settings

207

cv2.imwrite('output.bmp', img)

208

```

209

210

---

211

212

```python { .api }

213

cv2.imencode(ext: str, img: np.ndarray, params: list[int] = None) -> tuple[bool, np.ndarray]

214

```

215

216

Encodes an image into a memory buffer.

217

218

**Parameters:**

219

- `ext` (str): File extension defining output format (e.g., '.jpg', '.png')

220

- `img` (np.ndarray): Image array to encode

221

- `params` (list[int], optional): Format-specific parameters (same as `cv2.imwrite()`)

222

223

**Returns:**

224

- `tuple[bool, np.ndarray]`: Tuple of (success, encoded_buffer)

225

- `success` (bool): `True` if encoding succeeded

226

- `encoded_buffer` (np.ndarray): Encoded image as byte array

227

228

**Example:**

229

```python

230

import cv2

231

232

img = cv2.imread('photo.jpg')

233

234

# Encode as JPEG

235

success, buffer = cv2.imencode('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 85])

236

237

if success:

238

# Write buffer to file

239

with open('encoded.jpg', 'wb') as f:

240

f.write(buffer.tobytes())

241

242

# Or send over network

243

# socket.send(buffer.tobytes())

244

```

245

246

---

247

248

```python { .api }

249

cv2.haveImageWriter(filename: str) -> bool

250

```

251

252

Checks if an image writer for the specified format is available.

253

254

**Parameters:**

255

- `filename` (str): File path or filename with extension

256

257

**Returns:**

258

- `bool`: `True` if writer is available, `False` otherwise

259

260

**Example:**

261

```python

262

if cv2.haveImageWriter('output.jp2'):

263

cv2.imwrite('output.jp2', img)

264

else:

265

cv2.imwrite('output.jpg', img)

266

```

267

268

### Video Capture

269

270

The `VideoCapture` class provides functionality for capturing video from files or cameras.

271

272

```python { .api }

273

class cv2.VideoCapture:

274

def __init__(self, index: int | str, apiPreference: int = cv2.CAP_ANY)

275

```

276

277

Creates a video capture object for reading from a camera or video file.

278

279

**Parameters:**

280

- `index` (int | str): Device index (0, 1, 2, ...) or video file path

281

- `apiPreference` (int, optional): Preferred capture API backend

282

283

**Example:**

284

```python

285

import cv2

286

287

# Open default camera

288

cap = cv2.VideoCapture(0)

289

290

# Open video file

291

cap = cv2.VideoCapture('video.mp4')

292

293

# Open camera with specific API

294

cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # DirectShow on Windows

295

```

296

297

---

298

299

```python { .api }

300

VideoCapture.isOpened(self) -> bool

301

```

302

303

Checks if video capture has been initialized successfully.

304

305

**Returns:**

306

- `bool`: `True` if capture is opened, `False` otherwise

307

308

**Example:**

309

```python

310

cap = cv2.VideoCapture('video.mp4')

311

if not cap.isOpened():

312

print("Error opening video file")

313

```

314

315

---

316

317

```python { .api }

318

VideoCapture.read(self) -> tuple[bool, np.ndarray]

319

```

320

321

Grabs, decodes, and returns the next video frame.

322

323

**Returns:**

324

- `tuple[bool, np.ndarray]`: Tuple of (success, frame)

325

- `success` (bool): `True` if frame was read successfully

326

- `frame` (np.ndarray): Decoded frame image

327

328

**Example:**

329

```python

330

cap = cv2.VideoCapture('video.mp4')

331

332

while True:

333

ret, frame = cap.read()

334

if not ret:

335

break

336

337

cv2.imshow('Frame', frame)

338

if cv2.waitKey(25) & 0xFF == ord('q'):

339

break

340

341

cap.release()

342

cv2.destroyAllWindows()

343

```

344

345

---

346

347

```python { .api }

348

VideoCapture.grab(self) -> bool

349

```

350

351

Grabs the next frame from video source without decoding.

352

353

**Returns:**

354

- `bool`: `True` if frame was grabbed successfully

355

356

**Note:** Use with `retrieve()` for fine-grained control over frame capture. Useful when synchronizing multiple cameras.

357

358

---

359

360

```python { .api }

361

VideoCapture.retrieve(self, image: np.ndarray = None, flag: int = 0) -> tuple[bool, np.ndarray]

362

```

363

364

Decodes and returns the grabbed video frame.

365

366

**Parameters:**

367

- `image` (np.ndarray, optional): Pre-allocated array for output

368

- `flag` (int, optional): Channel selection flag

369

370

**Returns:**

371

- `tuple[bool, np.ndarray]`: Tuple of (success, frame)

372

373

**Example:**

374

```python

375

# Fine-grained frame capture

376

cap1 = cv2.VideoCapture(0)

377

cap2 = cv2.VideoCapture(1)

378

379

# Synchronize capture

380

grabbed1 = cap1.grab()

381

grabbed2 = cap2.grab()

382

383

if grabbed1 and grabbed2:

384

ret1, frame1 = cap1.retrieve()

385

ret2, frame2 = cap2.retrieve()

386

```

387

388

---

389

390

```python { .api }

391

VideoCapture.get(self, propId: int) -> float

392

```

393

394

Gets a video capture property value.

395

396

**Parameters:**

397

- `propId` (int): Property identifier (see Video Capture Properties section)

398

399

**Returns:**

400

- `float`: Property value

401

402

**Example:**

403

```python

404

cap = cv2.VideoCapture('video.mp4')

405

406

# Get video properties

407

width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

408

height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

409

fps = cap.get(cv2.CAP_PROP_FPS)

410

frame_count = cap.get(cv2.CAP_PROP_FRAME_COUNT)

411

412

print(f"Video: {width}x{height} @ {fps} fps, {frame_count} frames")

413

```

414

415

---

416

417

```python { .api }

418

VideoCapture.set(self, propId: int, value: float) -> bool

419

```

420

421

Sets a video capture property.

422

423

**Parameters:**

424

- `propId` (int): Property identifier

425

- `value` (float): New property value

426

427

**Returns:**

428

- `bool`: `True` if property was set successfully

429

430

**Example:**

431

```python

432

cap = cv2.VideoCapture(0)

433

434

# Set camera resolution

435

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)

436

cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)

437

438

# Set camera FPS

439

cap.set(cv2.CAP_PROP_FPS, 30)

440

441

# Jump to specific frame in video file

442

cap.set(cv2.CAP_PROP_POS_FRAMES, 100)

443

```

444

445

---

446

447

```python { .api }

448

VideoCapture.release(self) -> None

449

```

450

451

Closes video file or capturing device and releases resources.

452

453

**Example:**

454

```python

455

cap = cv2.VideoCapture('video.mp4')

456

# ... process video ...

457

cap.release()

458

```

459

460

### Video Capture Properties

461

462

Property constants for use with `VideoCapture.get()` and `VideoCapture.set()`.

463

464

```python { .api }

465

# Position properties

466

cv2.CAP_PROP_POS_MSEC # Current position in milliseconds

467

cv2.CAP_PROP_POS_FRAMES # 0-based index of next frame

468

cv2.CAP_PROP_POS_AVI_RATIO # Relative position (0.0 to 1.0)

469

470

# Frame properties

471

cv2.CAP_PROP_FRAME_WIDTH # Width of frames

472

cv2.CAP_PROP_FRAME_HEIGHT # Height of frames

473

cv2.CAP_PROP_FPS # Frame rate (frames per second)

474

cv2.CAP_PROP_FOURCC # 4-character codec code

475

cv2.CAP_PROP_FRAME_COUNT # Total number of frames

476

477

# Camera properties

478

cv2.CAP_PROP_BRIGHTNESS # Brightness setting

479

cv2.CAP_PROP_CONTRAST # Contrast setting

480

cv2.CAP_PROP_SATURATION # Saturation setting

481

cv2.CAP_PROP_HUE # Hue setting

482

cv2.CAP_PROP_GAIN # Gain setting

483

cv2.CAP_PROP_EXPOSURE # Exposure setting

484

485

# Auto settings

486

cv2.CAP_PROP_AUTOFOCUS # Auto-focus enable (0 or 1)

487

cv2.CAP_PROP_AUTO_EXPOSURE # Auto-exposure mode

488

```

489

490

**Example:**

491

```python

492

import cv2

493

494

cap = cv2.VideoCapture('video.mp4')

495

496

# Read video metadata

497

properties = {

498

'Width': cap.get(cv2.CAP_PROP_FRAME_WIDTH),

499

'Height': cap.get(cv2.CAP_PROP_FRAME_HEIGHT),

500

'FPS': cap.get(cv2.CAP_PROP_FPS),

501

'Frame Count': cap.get(cv2.CAP_PROP_FRAME_COUNT),

502

'FourCC': int(cap.get(cv2.CAP_PROP_FOURCC)),

503

}

504

505

# Navigate video

506

current_frame = cap.get(cv2.CAP_PROP_POS_FRAMES)

507

cap.set(cv2.CAP_PROP_POS_FRAMES, current_frame + 100) # Skip 100 frames

508

509

# Seek by time

510

cap.set(cv2.CAP_PROP_POS_MSEC, 5000) # Jump to 5 seconds

511

```

512

513

### Video Writing

514

515

The `VideoWriter` class enables writing video files with various codecs.

516

517

```python { .api }

518

class cv2.VideoWriter:

519

def __init__(self, filename: str, fourcc: int, fps: float,

520

frameSize: tuple[int, int], isColor: bool = True)

521

```

522

523

Creates a video writer object.

524

525

**Parameters:**

526

- `filename` (str): Output video file path

527

- `fourcc` (int): 4-character codec code (use `cv2.VideoWriter_fourcc()`)

528

- `fps` (float): Frame rate of output video

529

- `frameSize` (tuple[int, int]): Frame size as (width, height)

530

- `isColor` (bool, optional): If `True`, write color frames; if `False`, grayscale

531

532

**Example:**

533

```python

534

import cv2

535

536

# Create video writer for MP4 file

537

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

538

out = cv2.VideoWriter('output.mp4', fourcc, 30.0, (640, 480))

539

540

# Create grayscale video writer

541

out_gray = cv2.VideoWriter('output.avi', fourcc, 25.0, (640, 480), False)

542

```

543

544

---

545

546

```python { .api }

547

VideoWriter.isOpened(self) -> bool

548

```

549

550

Checks if video writer has been initialized successfully.

551

552

**Returns:**

553

- `bool`: `True` if writer is ready, `False` otherwise

554

555

**Example:**

556

```python

557

fourcc = cv2.VideoWriter_fourcc(*'XVID')

558

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

559

560

if not out.isOpened():

561

print("Error: Could not open video writer")

562

```

563

564

---

565

566

```python { .api }

567

VideoWriter.write(self, image: np.ndarray) -> None

568

```

569

570

Writes a frame to the video file.

571

572

**Parameters:**

573

- `image` (np.ndarray): Frame to write (must match size and color format)

574

575

**Example:**

576

```python

577

import cv2

578

import numpy as np

579

580

fourcc = cv2.VideoWriter_fourcc(*'XVID')

581

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

582

583

# Write frames

584

for i in range(100):

585

# Create or capture frame

586

frame = np.random.randint(0, 255, (480, 640, 3), dtype=np.uint8)

587

out.write(frame)

588

589

out.release()

590

```

591

592

---

593

594

```python { .api }

595

VideoWriter.release(self) -> None

596

```

597

598

Closes the video writer and finalizes the output file.

599

600

**Example:**

601

```python

602

out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))

603

# ... write frames ...

604

out.release() # Important: finalizes the video file

605

```

606

607

---

608

609

```python { .api }

610

VideoWriter.get(self, propId: int) -> float

611

```

612

613

Gets a video writer property value.

614

615

**Parameters:**

616

- `propId` (int): Property identifier

617

618

**Returns:**

619

- `float`: Property value

620

621

---

622

623

```python { .api }

624

VideoWriter.set(self, propId: int, value: float) -> bool

625

```

626

627

Sets a video writer property.

628

629

**Parameters:**

630

- `propId` (int): Property identifier

631

- `value` (float): New property value

632

633

**Returns:**

634

- `bool`: `True` if successful

635

636

### Video Codec Selection

637

638

```python { .api }

639

cv2.VideoWriter_fourcc(c1: str, c2: str, c3: str, c4: str) -> int

640

```

641

642

Creates a 4-character code (FourCC) for specifying video codecs.

643

644

**Parameters:**

645

- `c1, c2, c3, c4` (str): Four characters identifying the codec

646

647

**Returns:**

648

- `int`: FourCC code as integer

649

650

**Common Codecs:**

651

```python

652

# XVID (AVI container)

653

fourcc = cv2.VideoWriter_fourcc(*'XVID')

654

655

# MJPEG (AVI container)

656

fourcc = cv2.VideoWriter_fourcc(*'MJPG')

657

658

# H264 (MP4 container)

659

fourcc = cv2.VideoWriter_fourcc(*'H264')

660

fourcc = cv2.VideoWriter_fourcc(*'X264')

661

662

# MP4V (MP4 container)

663

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

664

fourcc = cv2.VideoWriter_fourcc(*'MP4V')

665

666

# FFV1 (lossless, AVI/MKV container)

667

fourcc = cv2.VideoWriter_fourcc(*'FFV1')

668

669

# Uncompressed (very large files)

670

fourcc = cv2.VideoWriter_fourcc(*'RGBA')

671

672

# Windows Media Video

673

fourcc = cv2.VideoWriter_fourcc(*'WMV1')

674

fourcc = cv2.VideoWriter_fourcc(*'WMV2')

675

676

# Motion JPEG 2000

677

fourcc = cv2.VideoWriter_fourcc(*'MJ2C')

678

679

# Platform-specific default

680

fourcc = cv2.VideoWriter_fourcc(*'DIVX') # Windows

681

fourcc = cv2.VideoWriter_fourcc(*'avc1') # macOS

682

```

683

684

**Example:**

685

```python

686

import cv2

687

688

cap = cv2.VideoCapture(0)

689

width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))

690

height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

691

692

# Create writer with XVID codec

693

fourcc = cv2.VideoWriter_fourcc(*'XVID')

694

out = cv2.VideoWriter('recording.avi', fourcc, 20.0, (width, height))

695

696

while True:

697

ret, frame = cap.read()

698

if not ret:

699

break

700

701

# Process frame

702

out.write(frame)

703

704

cv2.imshow('Recording', frame)

705

if cv2.waitKey(1) & 0xFF == ord('q'):

706

break

707

708

cap.release()

709

out.release()

710

cv2.destroyAllWindows()

711

```

712

713

### Complete Video Processing Example

714

715

```python

716

import cv2

717

718

# Read from video file

719

input_video = cv2.VideoCapture('input.mp4')

720

721

# Get video properties

722

fps = input_video.get(cv2.CAP_PROP_FPS)

723

width = int(input_video.get(cv2.CAP_PROP_FRAME_WIDTH))

724

height = int(input_video.get(cv2.CAP_PROP_FRAME_HEIGHT))

725

total_frames = int(input_video.get(cv2.CAP_PROP_FRAME_COUNT))

726

727

print(f"Processing video: {width}x{height} @ {fps} fps, {total_frames} frames")

728

729

# Create video writer

730

fourcc = cv2.VideoWriter_fourcc(*'mp4v')

731

output_video = cv2.VideoWriter('output.mp4', fourcc, fps, (width, height))

732

733

if not output_video.isOpened():

734

print("Error: Could not create output video")

735

input_video.release()

736

exit()

737

738

# Process each frame

739

frame_count = 0

740

while True:

741

ret, frame = input_video.read()

742

if not ret:

743

break

744

745

# Apply processing (example: convert to grayscale and back to BGR)

746

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

747

processed = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)

748

749

# Write processed frame

750

output_video.write(processed)

751

752

frame_count += 1

753

if frame_count % 30 == 0:

754

print(f"Processed {frame_count}/{total_frames} frames")

755

756

# Release resources

757

input_video.release()

758

output_video.release()

759

760

print(f"Video processing complete: {frame_count} frames written")

761

```

762

763

### Camera Capture Example

764

765

```python

766

import cv2

767

768

# Open default camera

769

cap = cv2.VideoCapture(0)

770

771

# Set camera properties

772

cap.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)

773

cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

774

cap.set(cv2.CAP_PROP_FPS, 30)

775

776

# Optional: adjust camera settings

777

cap.set(cv2.CAP_PROP_BRIGHTNESS, 128)

778

cap.set(cv2.CAP_PROP_CONTRAST, 128)

779

cap.set(cv2.CAP_PROP_SATURATION, 128)

780

781

if not cap.isOpened():

782

print("Error: Could not open camera")

783

exit()

784

785

# Get actual properties (may differ from requested)

786

actual_width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)

787

actual_height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)

788

actual_fps = cap.get(cv2.CAP_PROP_FPS)

789

790

print(f"Camera: {actual_width}x{actual_height} @ {actual_fps} fps")

791

792

# Create video writer for recording

793

fourcc = cv2.VideoWriter_fourcc(*'XVID')

794

out = cv2.VideoWriter('camera_recording.avi', fourcc, actual_fps,

795

(int(actual_width), int(actual_height)))

796

797

recording = False

798

799

while True:

800

ret, frame = cap.read()

801

if not ret:

802

print("Error: Failed to capture frame")

803

break

804

805

# Display recording status

806

if recording:

807

cv2.putText(frame, "REC", (10, 30), cv2.FONT_HERSHEY_SIMPLEX,

808

1, (0, 0, 255), 2)

809

out.write(frame)

810

811

cv2.imshow('Camera', frame)

812

813

# Handle keyboard input

814

key = cv2.waitKey(1) & 0xFF

815

if key == ord('q'):

816

break

817

elif key == ord('r'):

818

recording = not recording

819

print("Recording:", "ON" if recording else "OFF")

820

elif key == ord('s'):

821

# Save snapshot

822

cv2.imwrite('snapshot.jpg', frame, [cv2.IMWRITE_JPEG_QUALITY, 95])

823

print("Snapshot saved")

824

825

# Release resources

826

cap.release()

827

out.release()

828

cv2.destroyAllWindows()

829

```

830