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

core-operations.mddocs/

0

# Core Operations

1

2

Core operations in OpenCV provide fundamental array manipulation, mathematical operations, and linear algebra capabilities that form the foundation for image processing and computer vision tasks. These operations work on multi-dimensional arrays (Mat objects) and include arithmetic, logical, statistical, and transformation functions.

3

4

## Capabilities

5

6

### Arithmetic Operations

7

8

Element-wise arithmetic operations on arrays with support for saturation arithmetic, masking, and multiple data types.

9

10

#### Addition

11

12

```python { .api }

13

cv2.add(src1, src2, dst=None, mask=None, dtype=None) -> dst

14

```

15

16

Calculates the per-element sum of two arrays or an array and a scalar.

17

18

**Parameters:**

19

20

- `src1` (ndarray): First input array or scalar

21

- `src2` (ndarray): Second input array or scalar

22

- `dst` (ndarray, optional): Output array of the same size and type as input arrays

23

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

24

- `dtype` (int, optional): Optional depth of the output array

25

26

**Returns:**

27

28

- `dst` (ndarray): Output array

29

30

#### Subtraction

31

32

```python { .api }

33

cv2.subtract(src1, src2, dst=None, mask=None, dtype=None) -> dst

34

```

35

36

Calculates the per-element difference between two arrays or an array and a scalar.

37

38

**Parameters:**

39

40

- `src1` (ndarray): First input array or scalar

41

- `src2` (ndarray): Second input array or scalar

42

- `dst` (ndarray, optional): Output array of the same size and type as input arrays

43

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

44

- `dtype` (int, optional): Optional depth of the output array

45

46

**Returns:**

47

48

- `dst` (ndarray): Output array

49

50

#### Multiplication

51

52

```python { .api }

53

cv2.multiply(src1, src2, dst=None, scale=1.0, dtype=None) -> dst

54

```

55

56

Calculates the per-element scaled product of two arrays.

57

58

**Parameters:**

59

60

- `src1` (ndarray): First input array

61

- `src2` (ndarray): Second input array

62

- `dst` (ndarray, optional): Output array of the same size and type as input arrays

63

- `scale` (float, optional): Optional scale factor

64

- `dtype` (int, optional): Optional depth of the output array

65

66

**Returns:**

67

68

- `dst` (ndarray): Output array

69

70

#### Division

71

72

```python { .api }

73

cv2.divide(src1, src2, dst=None, scale=1.0, dtype=None) -> dst

74

```

75

76

Performs per-element division of two arrays or a scalar by an array.

77

78

**Parameters:**

79

80

- `src1` (ndarray): First input array (dividend)

81

- `src2` (ndarray): Second input array (divisor)

82

- `dst` (ndarray, optional): Output array of the same size and type as input arrays

83

- `scale` (float, optional): Optional scale factor

84

- `dtype` (int, optional): Optional depth of the output array

85

86

**Returns:**

87

88

- `dst` (ndarray): Output array

89

90

#### Absolute Difference

91

92

```python { .api }

93

cv2.absdiff(src1, src2, dst=None) -> dst

94

```

95

96

Calculates the per-element absolute difference between two arrays or between an array and a scalar.

97

98

**Parameters:**

99

100

- `src1` (ndarray): First input array or scalar

101

- `src2` (ndarray): Second input array or scalar

102

- `dst` (ndarray, optional): Output array

103

104

**Returns:**

105

106

- `dst` (ndarray): Output array of the same size and type as input arrays

107

108

#### Weighted Addition

109

110

```python { .api }

111

cv2.addWeighted(src1, alpha, src2, beta, gamma, dst=None, dtype=None) -> dst

112

```

113

114

Calculates the weighted sum of two arrays: dst = src1 * alpha + src2 * beta + gamma.

115

116

**Parameters:**

117

118

- `src1` (ndarray): First input array

119

- `alpha` (float): Weight of the first array elements

120

- `src2` (ndarray): Second input array of the same size and channel number as src1

121

- `beta` (float): Weight of the second array elements

122

- `gamma` (float): Scalar added to each sum

123

- `dst` (ndarray, optional): Output array

124

- `dtype` (int, optional): Optional depth of the output array

125

126

**Returns:**

127

128

- `dst` (ndarray): Output array

129

130

### Logical Operations

131

132

Bitwise logical operations on arrays, commonly used for masking and binary image manipulation.

133

134

#### Bitwise AND

135

136

```python { .api }

137

cv2.bitwise_and(src1, src2, dst=None, mask=None) -> dst

138

```

139

140

Calculates the per-element bit-wise conjunction of two arrays or an array and a scalar.

141

142

**Parameters:**

143

144

- `src1` (ndarray): First input array or scalar

145

- `src2` (ndarray): Second input array or scalar

146

- `dst` (ndarray, optional): Output array

147

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

148

149

**Returns:**

150

151

- `dst` (ndarray): Output array

152

153

#### Bitwise OR

154

155

```python { .api }

156

cv2.bitwise_or(src1, src2, dst=None, mask=None) -> dst

157

```

158

159

Calculates the per-element bit-wise disjunction of two arrays or an array and a scalar.

160

161

**Parameters:**

162

163

- `src1` (ndarray): First input array or scalar

164

- `src2` (ndarray): Second input array or scalar

165

- `dst` (ndarray, optional): Output array

166

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

167

168

**Returns:**

169

170

- `dst` (ndarray): Output array

171

172

#### Bitwise XOR

173

174

```python { .api }

175

cv2.bitwise_xor(src1, src2, dst=None, mask=None) -> dst

176

```

177

178

Calculates the per-element bit-wise "exclusive or" operation on two arrays or an array and a scalar.

179

180

**Parameters:**

181

182

- `src1` (ndarray): First input array or scalar

183

- `src2` (ndarray): Second input array or scalar

184

- `dst` (ndarray, optional): Output array

185

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

186

187

**Returns:**

188

189

- `dst` (ndarray): Output array

190

191

#### Bitwise NOT

192

193

```python { .api }

194

cv2.bitwise_not(src, dst=None, mask=None) -> dst

195

```

196

197

Inverts every bit of an array.

198

199

**Parameters:**

200

201

- `src` (ndarray): Input array

202

- `dst` (ndarray, optional): Output array

203

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

204

205

**Returns:**

206

207

- `dst` (ndarray): Output array

208

209

### Mathematical Operations

210

211

Element-wise mathematical functions for arrays including square root, power, exponential, and logarithm.

212

213

#### Square Root

214

215

```python { .api }

216

cv2.sqrt(src, dst=None) -> dst

217

```

218

219

Calculates a square root of array elements.

220

221

**Parameters:**

222

223

- `src` (ndarray): Input floating-point array

224

- `dst` (ndarray, optional): Output array of the same size and type as src

225

226

**Returns:**

227

228

- `dst` (ndarray): Output array containing square roots of input elements

229

230

#### Power

231

232

```python { .api }

233

cv2.pow(src, power, dst=None) -> dst

234

```

235

236

Raises every array element to a power.

237

238

**Parameters:**

239

240

- `src` (ndarray): Input array

241

- `power` (float): Exponent of power

242

- `dst` (ndarray, optional): Output array of the same size and type as src

243

244

**Returns:**

245

246

- `dst` (ndarray): Output array with each element raised to the specified power

247

248

#### Exponential

249

250

```python { .api }

251

cv2.exp(src, dst=None) -> dst

252

```

253

254

Calculates the exponent of every array element.

255

256

**Parameters:**

257

258

- `src` (ndarray): Input array

259

- `dst` (ndarray, optional): Output array of the same size and type as src

260

261

**Returns:**

262

263

- `dst` (ndarray): Output array where dst[I] = e^(src(I))

264

265

#### Logarithm

266

267

```python { .api }

268

cv2.log(src, dst=None) -> dst

269

```

270

271

Calculates the natural logarithm of every array element.

272

273

**Parameters:**

274

275

- `src` (ndarray): Input array

276

- `dst` (ndarray, optional): Output array of the same size and type as src

277

278

**Returns:**

279

280

- `dst` (ndarray): Output array where dst(I) = log(src(I)). Output on zero, negative and special (NaN, Inf) values is undefined

281

282

#### Magnitude

283

284

```python { .api }

285

cv2.magnitude(x, y, magnitude=None) -> magnitude

286

```

287

288

Calculates the magnitude of 2D vectors.

289

290

**Parameters:**

291

292

- `x` (ndarray): Floating-point array of x-coordinates of the vectors

293

- `y` (ndarray): Floating-point array of y-coordinates of the vectors (same size as x)

294

- `magnitude` (ndarray, optional): Output array of the same size and type as x

295

296

**Returns:**

297

298

- `magnitude` (ndarray): Output array where magnitude(I) = sqrt(x(I)^2 + y(I)^2)

299

300

#### Phase

301

302

```python { .api }

303

cv2.phase(x, y, angle=None, angleInDegrees=False) -> angle

304

```

305

306

Calculates the rotation angle of 2D vectors.

307

308

**Parameters:**

309

310

- `x` (ndarray): Floating-point array of x-coordinates of the vectors

311

- `y` (ndarray): Floating-point array of y-coordinates of the vectors (same size as x)

312

- `angle` (ndarray, optional): Output array of angles (in radians or degrees)

313

- `angleInDegrees` (bool): When true, the function calculates the angle in degrees, otherwise in radians

314

315

**Returns:**

316

317

- `angle` (ndarray): Output array of vector angles

318

319

#### Cartesian to Polar Coordinates

320

321

```python { .api }

322

cv2.cartToPolar(x, y, magnitude=None, angle=None, angleInDegrees=False) -> magnitude, angle

323

```

324

325

Calculates the magnitude and angle of 2D vectors.

326

327

**Parameters:**

328

329

- `x` (ndarray): Array of x-coordinates (must be single-precision or double-precision floating-point)

330

- `y` (ndarray): Array of y-coordinates (same size and type as x)

331

- `magnitude` (ndarray, optional): Output array of magnitudes

332

- `angle` (ndarray, optional): Output array of angles (in radians or degrees)

333

- `angleInDegrees` (bool): When true, the angles are measured in degrees (0-360), otherwise in radians (0-2*pi)

334

335

**Returns:**

336

337

- `magnitude` (ndarray): Output array of magnitudes

338

- `angle` (ndarray): Output array of angles

339

340

#### Polar to Cartesian Coordinates

341

342

```python { .api }

343

cv2.polarToCart(magnitude, angle, x=None, y=None, angleInDegrees=False) -> x, y

344

```

345

346

Calculates x and y coordinates of 2D vectors from their magnitude and angle.

347

348

**Parameters:**

349

350

- `magnitude` (ndarray): Input array of magnitudes (floating-point)

351

- `angle` (ndarray): Input array of angles (in radians or degrees)

352

- `x` (ndarray, optional): Output array of x-coordinates (same size and type as magnitude)

353

- `y` (ndarray, optional): Output array of y-coordinates (same size and type as magnitude)

354

- `angleInDegrees` (bool): When true, the input angles are measured in degrees, otherwise in radians

355

356

**Returns:**

357

358

- `x` (ndarray): Output array of x-coordinates

359

- `y` (ndarray): Output array of y-coordinates

360

361

#### Scaled Addition

362

363

```python { .api }

364

cv2.scaleAdd(src1, alpha, src2, dst=None) -> dst

365

```

366

367

Calculates the sum of a scaled array and another array.

368

369

**Parameters:**

370

371

- `src1` (ndarray): First input array

372

- `alpha` (float): Scale factor for the first array

373

- `src2` (ndarray): Second input array (same size and type as src1)

374

- `dst` (ndarray, optional): Output array

375

376

**Returns:**

377

378

- `dst` (ndarray): Output array where dst = src1 * alpha + src2

379

380

### Comparison and Min/Max Operations

381

382

Element-wise comparison and minimum/maximum operations for array analysis and thresholding.

383

384

#### Comparison

385

386

```python { .api }

387

cv2.compare(src1, src2, cmpop) -> dst

388

```

389

390

Performs per-element comparison of two arrays.

391

392

**Parameters:**

393

394

- `src1` (ndarray): First input array or scalar

395

- `src2` (ndarray): Second input array or scalar

396

- `cmpop` (int): Flag specifying the relation between elements to be checked

397

- `cv2.CMP_EQ`: src1 equal to src2

398

- `cv2.CMP_GT`: src1 greater than src2

399

- `cv2.CMP_GE`: src1 greater than or equal to src2

400

- `cv2.CMP_LT`: src1 less than src2

401

- `cv2.CMP_LE`: src1 less than or equal to src2

402

- `cv2.CMP_NE`: src1 not equal to src2

403

404

**Returns:**

405

406

- `dst` (ndarray): Output array of type CV_8U with elements set to 255 (true) or 0 (false)

407

408

#### Element-wise Minimum

409

410

```python { .api }

411

cv2.min(src1, src2, dst=None) -> dst

412

```

413

414

Calculates per-element minimum of two arrays or an array and a scalar.

415

416

**Parameters:**

417

418

- `src1` (ndarray): First input array or scalar

419

- `src2` (ndarray): Second input array or scalar

420

- `dst` (ndarray, optional): Output array

421

422

**Returns:**

423

424

- `dst` (ndarray): Output array of the same size and type as input arrays

425

426

#### Element-wise Maximum

427

428

```python { .api }

429

cv2.max(src1, src2, dst=None) -> dst

430

```

431

432

Calculates per-element maximum of two arrays or an array and a scalar.

433

434

**Parameters:**

435

436

- `src1` (ndarray): First input array or scalar

437

- `src2` (ndarray): Second input array or scalar

438

- `dst` (ndarray, optional): Output array

439

440

**Returns:**

441

442

- `dst` (ndarray): Output array of the same size and type as input arrays

443

444

### Array Statistics

445

446

Statistical operations for analyzing array contents, including norms, means, and extrema.

447

448

#### Mean

449

450

```python { .api }

451

cv2.mean(src, mask=None) -> retval

452

```

453

454

Calculates an average (mean) of array elements.

455

456

**Parameters:**

457

458

- `src` (ndarray): Input array that should have from 1 to 4 channels so that the result can be stored in Scalar_

459

- `mask` (ndarray, optional): Optional operation mask

460

461

**Returns:**

462

463

- `retval` (Scalar): Mean value for each channel. When all mask elements are 0, the function returns Scalar::all(0)

464

465

#### Norm Calculation

466

467

```python { .api }

468

cv2.norm(src1, normType=None, mask=None) -> retval

469

cv2.norm(src1, src2, normType=None, mask=None) -> retval

470

```

471

472

Calculates an absolute array norm, absolute difference norm, or relative difference norm.

473

474

**Parameters:**

475

476

- `src1` (ndarray): First input array

477

- `src2` (ndarray, optional): Second input array of the same size and type as src1

478

- `normType` (int, optional): Type of norm to calculate

479

- `cv2.NORM_INF`: Max norm

480

- `cv2.NORM_L1`: L1 norm

481

- `cv2.NORM_L2`: L2 norm (default)

482

- `cv2.NORM_L2SQR`: Squared L2 norm

483

- `cv2.NORM_HAMMING`: Hamming norm

484

- `cv2.NORM_HAMMING2`: Hamming norm with two bits per element

485

- `mask` (ndarray, optional): Optional operation mask, 8-bit single channel array

486

487

**Returns:**

488

489

- `retval` (float): Calculated norm value

490

491

#### Normalization

492

493

```python { .api }

494

cv2.normalize(src, dst=None, alpha=1.0, beta=0.0, norm_type=cv2.NORM_L2,

495

dtype=None, mask=None) -> dst

496

```

497

498

Normalizes the norm or value range of an array.

499

500

**Parameters:**

501

502

- `src` (ndarray): Input array

503

- `dst` (ndarray, optional): Output array of the same size as src

504

- `alpha` (float): Norm value to normalize to or lower range boundary in range normalization

505

- `beta` (float): Upper range boundary in range normalization

506

- `norm_type` (int): Normalization type

507

- `cv2.NORM_INF`, `cv2.NORM_L1`, `cv2.NORM_L2`: For norm normalization

508

- `cv2.NORM_MINMAX`: For range normalization

509

- `dtype` (int, optional): Output array depth

510

- `mask` (ndarray, optional): Optional operation mask

511

512

**Returns:**

513

514

- `dst` (ndarray): Normalized array

515

516

#### Mean and Standard Deviation

517

518

```python { .api }

519

cv2.meanStdDev(src, mean=None, stddev=None, mask=None) -> mean, stddev

520

```

521

522

Calculates mean and standard deviation of array elements.

523

524

**Parameters:**

525

526

- `src` (ndarray): Input array

527

- `mean` (ndarray, optional): Output parameter for calculated mean

528

- `stddev` (ndarray, optional): Output parameter for calculated standard deviation

529

- `mask` (ndarray, optional): Optional operation mask

530

531

**Returns:**

532

533

- `mean` (ndarray): Mean value of array elements per channel

534

- `stddev` (ndarray): Standard deviation of array elements per channel

535

536

#### Global Minimum and Maximum

537

538

```python { .api }

539

cv2.minMaxLoc(src, mask=None) -> minVal, maxVal, minLoc, maxLoc

540

```

541

542

Finds the global minimum and maximum in an array.

543

544

**Parameters:**

545

546

- `src` (ndarray): Input single-channel array

547

- `mask` (ndarray, optional): Optional mask to select a sub-array

548

549

**Returns:**

550

551

- `minVal` (float): Minimum value

552

- `maxVal` (float): Maximum value

553

- `minLoc` (tuple): Position of minimum value (x, y)

554

- `maxLoc` (tuple): Position of maximum value (x, y)

555

556

#### Count Non-Zero Elements

557

558

```python { .api }

559

cv2.countNonZero(src) -> retval

560

```

561

562

Counts non-zero array elements.

563

564

**Parameters:**

565

566

- `src` (ndarray): Single-channel array

567

568

**Returns:**

569

570

- `retval` (int): Number of non-zero elements

571

572

#### Sum of Elements

573

574

```python { .api }

575

cv2.sum(src) -> retval

576

cv2.sumElems(src) -> retval

577

```

578

579

Calculates the sum of array elements.

580

581

**Parameters:**

582

583

- `src` (ndarray): Input array

584

585

**Returns:**

586

587

- `retval` (Scalar): Sum of array elements per channel

588

589

### Channel Operations

590

591

Operations for manipulating multi-channel arrays, essential for working with color images.

592

593

#### Split Channels

594

595

```python { .api }

596

cv2.split(src) -> mv

597

```

598

599

Divides a multi-channel array into several single-channel arrays.

600

601

**Parameters:**

602

603

- `src` (ndarray): Input multi-channel array

604

605

**Returns:**

606

607

- `mv` (list of ndarray): List of single-channel arrays

608

609

#### Merge Channels

610

611

```python { .api }

612

cv2.merge(mv, dst=None) -> dst

613

```

614

615

Merges several single-channel arrays into a multi-channel array.

616

617

**Parameters:**

618

619

- `mv` (list of ndarray): Input list of single-channel arrays to be merged

620

- `dst` (ndarray, optional): Output array

621

622

**Returns:**

623

624

- `dst` (ndarray): Output multi-channel array

625

626

#### Mix Channels

627

628

```python { .api }

629

cv2.mixChannels(src, dst, fromTo) -> dst

630

```

631

632

Copies specified channels from input arrays to specified channels of output arrays.

633

634

**Parameters:**

635

636

- `src` (list of ndarray): Input array or list of input arrays

637

- `dst` (list of ndarray): Output array or list of output arrays

638

- `fromTo` (list of int): List of index pairs specifying which channels are copied

639

- Format: [from_channel, to_channel, from_channel, to_channel, ...]

640

641

**Returns:**

642

643

- `dst` (list of ndarray): Output arrays

644

645

#### Extract Channel

646

647

```python { .api }

648

cv2.extractChannel(src, coi, dst=None) -> dst

649

```

650

651

Extracts a single channel from a multi-channel array.

652

653

**Parameters:**

654

655

- `src` (ndarray): Input multi-channel array

656

- `coi` (int): Index of channel to extract (0-based)

657

- `dst` (ndarray, optional): Output array

658

659

**Returns:**

660

661

- `dst` (ndarray): Single-channel output array

662

663

#### Insert Channel

664

665

```python { .api }

666

cv2.insertChannel(src, dst, coi) -> dst

667

```

668

669

Inserts a single channel into a multi-channel array.

670

671

**Parameters:**

672

673

- `src` (ndarray): Input single-channel array to be inserted

674

- `dst` (ndarray): Target multi-channel array

675

- `coi` (int): Index of channel to insert into (0-based)

676

677

**Returns:**

678

679

- `dst` (ndarray): Modified multi-channel array

680

681

### Array Transformations

682

683

Geometric transformations and manipulations of array structure.

684

685

#### Flip

686

687

```python { .api }

688

cv2.flip(src, flipCode, dst=None) -> dst

689

```

690

691

Flips an array around vertical, horizontal, or both axes.

692

693

**Parameters:**

694

695

- `src` (ndarray): Input array

696

- `flipCode` (int): Flag to specify how to flip the array

697

- `0`: Flip vertically (around x-axis)

698

- `> 0`: Flip horizontally (around y-axis)

699

- `< 0`: Flip both vertically and horizontally

700

- `dst` (ndarray, optional): Output array

701

702

**Returns:**

703

704

- `dst` (ndarray): Output array of the same type as src

705

706

#### Rotate

707

708

```python { .api }

709

cv2.rotate(src, rotateCode, dst=None) -> dst

710

```

711

712

Rotates an array by 90, 180, or 270 degrees.

713

714

**Parameters:**

715

716

- `src` (ndarray): Input array

717

- `rotateCode` (int): Rotation direction

718

- `cv2.ROTATE_90_CLOCKWISE`: Rotate 90 degrees clockwise

719

- `cv2.ROTATE_180`: Rotate 180 degrees

720

- `cv2.ROTATE_90_COUNTERCLOCKWISE`: Rotate 90 degrees counterclockwise

721

- `dst` (ndarray, optional): Output array

722

723

**Returns:**

724

725

- `dst` (ndarray): Output rotated array

726

727

#### Transpose

728

729

```python { .api }

730

cv2.transpose(src, dst=None) -> dst

731

```

732

733

Transposes a matrix (swaps rows and columns).

734

735

**Parameters:**

736

737

- `src` (ndarray): Input array

738

- `dst` (ndarray, optional): Output array

739

740

**Returns:**

741

742

- `dst` (ndarray): Transposed array

743

744

#### Repeat

745

746

```python { .api }

747

cv2.repeat(src, ny, nx, dst=None) -> dst

748

```

749

750

Fills the output array with repeated copies of the input array.

751

752

**Parameters:**

753

754

- `src` (ndarray): Input array to replicate

755

- `ny` (int): Number of times to repeat the array along the vertical axis

756

- `nx` (int): Number of times to repeat the array along the horizontal axis

757

- `dst` (ndarray, optional): Output array

758

759

**Returns:**

760

761

- `dst` (ndarray): Output array

762

763

#### Horizontal Concatenation

764

765

```python { .api }

766

cv2.hconcat(src, dst=None) -> dst

767

```

768

769

Applies horizontal concatenation to given matrices.

770

771

**Parameters:**

772

773

- `src` (list of ndarray): Input arrays to concatenate (must have the same number of rows)

774

- `dst` (ndarray, optional): Output array

775

776

**Returns:**

777

778

- `dst` (ndarray): Horizontally concatenated array

779

780

#### Vertical Concatenation

781

782

```python { .api }

783

cv2.vconcat(src, dst=None) -> dst

784

```

785

786

Applies vertical concatenation to given matrices.

787

788

**Parameters:**

789

790

- `src` (list of ndarray): Input arrays to concatenate (must have the same number of columns)

791

- `dst` (ndarray, optional): Output array

792

793

**Returns:**

794

795

- `dst` (ndarray): Vertically concatenated array

796

797

### Range and LUT Operations

798

799

Operations for value range checking and lookup table transformations.

800

801

#### In Range

802

803

```python { .api }

804

cv2.inRange(src, lowerb, upperb, dst=None) -> dst

805

```

806

807

Checks if array elements lie between the elements of two other arrays or scalars.

808

809

**Parameters:**

810

811

- `src` (ndarray): Input array

812

- `lowerb` (ndarray or scalar): Inclusive lower boundary array or scalar

813

- `upperb` (ndarray or scalar): Inclusive upper boundary array or scalar

814

- `dst` (ndarray, optional): Output array

815

816

**Returns:**

817

818

- `dst` (ndarray): Output array of type CV_8U with elements set to 255 (within range) or 0 (outside range)

819

820

#### Look-Up Table Transform

821

822

```python { .api }

823

cv2.LUT(src, lut, dst=None) -> dst

824

```

825

826

Performs a look-up table transform of an array.

827

828

**Parameters:**

829

830

- `src` (ndarray): Input array of 8-bit elements

831

- `lut` (ndarray): Look-up table of 256 elements; should have the same depth as the output array

832

- `dst` (ndarray, optional): Output array

833

834

**Returns:**

835

836

- `dst` (ndarray): Output array of the same size and number of channels as src

837

838

### Reduction Operations

839

840

Operations that reduce arrays to vectors or scalars.

841

842

#### Reduce

843

844

```python { .api }

845

cv2.reduce(src, dim, rtype, dst=None, dtype=None) -> dst

846

```

847

848

Reduces a matrix to a vector.

849

850

**Parameters:**

851

852

- `src` (ndarray): Input 2D matrix

853

- `dim` (int): Dimension index along which the reduction is performed

854

- `0`: Reduce to a single row

855

- `1`: Reduce to a single column

856

- `rtype` (int): Reduction operation type

857

- `cv2.REDUCE_SUM`: Sum over all rows/columns

858

- `cv2.REDUCE_AVG`: Mean over all rows/columns

859

- `cv2.REDUCE_MAX`: Maximum over all rows/columns

860

- `cv2.REDUCE_MIN`: Minimum over all rows/columns

861

- `dst` (ndarray, optional): Output vector

862

- `dtype` (int, optional): Output array depth

863

864

**Returns:**

865

866

- `dst` (ndarray): Output vector

867

868

### Linear Algebra Operations

869

870

Matrix operations and linear algebra computations.

871

872

#### Solve Linear System

873

874

```python { .api }

875

cv2.solve(src1, src2, flags=cv2.DECOMP_LU) -> retval, dst

876

```

877

878

Solves one or more linear systems or least-squares problems.

879

880

**Parameters:**

881

882

- `src1` (ndarray): Input matrix on the left-hand side of the system

883

- `src2` (ndarray): Input matrix on the right-hand side of the system

884

- `flags` (int): Solution method

885

- `cv2.DECOMP_LU`: Gaussian elimination with optimal pivot element

886

- `cv2.DECOMP_SVD`: Singular value decomposition (SVD)

887

- `cv2.DECOMP_EIG`: Eigenvalue decomposition

888

- `cv2.DECOMP_CHOLESKY`: Cholesky factorization

889

- `cv2.DECOMP_QR`: QR factorization

890

- `cv2.DECOMP_NORMAL`: Use normal equations (for overdetermined systems)

891

892

**Returns:**

893

894

- `retval` (bool): True if the system has a solution

895

- `dst` (ndarray): Output solution

896

897

#### Matrix Inversion

898

899

```python { .api }

900

cv2.invert(src, flags=cv2.DECOMP_LU) -> retval, dst

901

```

902

903

Finds the inverse or pseudo-inverse of a matrix.

904

905

**Parameters:**

906

907

- `src` (ndarray): Input floating-point M×N matrix

908

- `flags` (int): Inversion method

909

- `cv2.DECOMP_LU`: Gaussian elimination (for square matrices)

910

- `cv2.DECOMP_SVD`: Singular value decomposition (for any matrices)

911

- `cv2.DECOMP_CHOLESKY`: Cholesky factorization (for symmetric positive-definite matrices)

912

913

**Returns:**

914

915

- `retval` (float): Inverse condition number (DECOMP_LU) or 0 if singular

916

- `dst` (ndarray): Output inverse matrix

917

918

#### Eigenvalues and Eigenvectors

919

920

```python { .api }

921

cv2.eigen(src, computeEigenvectors=True) -> retval, eigenvalues, eigenvectors

922

```

923

924

Calculates eigenvalues and eigenvectors of a symmetric matrix.

925

926

**Parameters:**

927

928

- `src` (ndarray): Input symmetric square matrix

929

- `computeEigenvectors` (bool): Flag indicating whether eigenvectors should be computed

930

931

**Returns:**

932

933

- `retval` (bool): True if eigenvalues/eigenvectors were computed successfully

934

- `eigenvalues` (ndarray): Output vector of eigenvalues (sorted in descending order)

935

- `eigenvectors` (ndarray): Output matrix of eigenvectors (one per row)

936

937

#### Determinant

938

939

```python { .api }

940

cv2.determinant(src) -> retval

941

```

942

943

Returns the determinant of a square floating-point matrix.

944

945

**Parameters:**

946

947

- `src` (ndarray): Input square matrix

948

949

**Returns:**

950

951

- `retval` (float): Determinant of the matrix

952

953

#### Singular Value Decomposition

954

955

```python { .api }

956

cv2.SVDecomp(src, flags=0) -> retval, w, u, vt

957

```

958

959

Performs singular value decomposition of a matrix.

960

961

**Parameters:**

962

963

- `src` (ndarray): Input M×N matrix

964

- `flags` (int): Operation flags

965

- `cv2.SVD_MODIFY_A`: Allows the function to modify the input matrix

966

- `cv2.SVD_NO_UV`: Only singular values are computed

967

- `cv2.SVD_FULL_UV`: Full-size U and V are computed

968

969

**Returns:**

970

971

- `retval` (bool): True if decomposition was successful

972

- `w` (ndarray): Output vector of singular values

973

- `u` (ndarray): Output left singular vectors (M×M or M×min(M,N))

974

- `vt` (ndarray): Output right singular vectors transposed (N×N or min(M,N)×N)

975

976

#### Principal Component Analysis

977

978

```python { .api }

979

cv2.PCACompute(data, mean, maxComponents=0) -> mean, eigenvectors, eigenvalues

980

cv2.PCACompute2(data, mean, maxComponents=0, retainedVariance=0) -> mean, eigenvectors, eigenvalues

981

```

982

983

Performs Principal Component Analysis on a set of vectors.

984

985

**Parameters:**

986

987

- `data` (ndarray): Input data matrix where each row is a sample vector

988

- `mean` (ndarray): Input/output mean vector (if empty, computed from data)

989

- `maxComponents` (int): Maximum number of components to retain

990

- `retainedVariance` (float, PCACompute2 only): Percentage of variance to retain (0-1)

991

992

**Returns:**

993

994

- `mean` (ndarray): Mean vector of the input data

995

- `eigenvectors` (ndarray): Principal components (eigenvectors of covariance matrix)

996

- `eigenvalues` (ndarray): Eigenvalues corresponding to the eigenvectors

997

998

#### General Matrix Multiplication

999

1000

```python { .api }

1001

cv2.gemm(src1, src2, alpha, src3, beta, flags=0, dst=None) -> dst

1002

```

1003

1004

Performs generalized matrix multiplication: dst = alpha * src1 * src2 + beta * src3.

1005

1006

**Parameters:**

1007

1008

- `src1` (ndarray): First input matrix

1009

- `src2` (ndarray): Second input matrix

1010

- `alpha` (float): Weight of the matrix product

1011

- `src3` (ndarray): Third input matrix added to the product

1012

- `beta` (float): Weight of src3

1013

- `flags` (int): Operation flags

1014

- `cv2.GEMM_1_T`: Transpose src1

1015

- `cv2.GEMM_2_T`: Transpose src2

1016

- `cv2.GEMM_3_T`: Transpose src3

1017

- `dst` (ndarray, optional): Output matrix

1018

1019

**Returns:**

1020

1021

- `dst` (ndarray): Output matrix

1022

1023

#### Transform

1024

1025

```python { .api }

1026

cv2.transform(src, m, dst=None) -> dst

1027

```

1028

1029

Performs matrix transformation of every array element.

1030

1031

**Parameters:**

1032

1033

- `src` (ndarray): Input array (must be of floating-point type)

1034

- `m` (ndarray): Transformation matrix (2×2, 2×3, 3×3, or 3×4)

1035

- `dst` (ndarray, optional): Output array

1036

1037

**Returns:**

1038

1039

- `dst` (ndarray): Output array with the same size and depth as src

1040

1041

#### Perspective Transform

1042

1043

```python { .api }

1044

cv2.perspectiveTransform(src, m, dst=None) -> dst

1045

```

1046

1047

Performs perspective transformation of vectors.

1048

1049

**Parameters:**

1050

1051

- `src` (ndarray): Input two-channel or three-channel floating-point array (each element is a 2D/3D vector)

1052

- `m` (ndarray): 3×3 or 4×4 floating-point transformation matrix

1053

- `dst` (ndarray, optional): Output array

1054

1055

**Returns:**

1056

1057

- `dst` (ndarray): Output array with the same size and type as src

1058

1059

#### Mahalanobis Distance

1060

1061

```python { .api }

1062

cv2.Mahalanobis(v1, v2, icovar) -> retval

1063

```

1064

1065

Calculates the Mahalanobis distance between two vectors.

1066

1067

**Parameters:**

1068

1069

- `v1` (ndarray): First input vector

1070

- `v2` (ndarray): Second input vector

1071

- `icovar` (ndarray): Inverse covariance matrix

1072

1073

**Returns:**

1074

1075

- `retval` (float): Mahalanobis distance

1076

1077

#### Multiply Transposed

1078

1079

```python { .api }

1080

cv2.mulTransposed(src, aTa, dst=None, delta=None, scale=1.0, dtype=None) -> dst

1081

```

1082

1083

Calculates the product of a matrix and its transpose.

1084

1085

**Parameters:**

1086

1087

- `src` (ndarray): Input single-channel matrix

1088

- `aTa` (bool): Flag specifying multiplication ordering

1089

- `True`: dst = scale * (src - delta)^T * (src - delta)

1090

- `False`: dst = scale * (src - delta) * (src - delta)^T

1091

- `dst` (ndarray, optional): Output square matrix

1092

- `delta` (ndarray, optional): Optional delta matrix subtracted from src

1093

- `scale` (float): Optional scale factor

1094

- `dtype` (int, optional): Output matrix depth

1095

1096

**Returns:**

1097

1098

- `dst` (ndarray): Output matrix

1099

1100

#### Set Identity

1101

1102

```python { .api }

1103

cv2.setIdentity(mtx, s=1.0) -> mtx

1104

```

1105

1106

Initializes a scaled identity matrix.

1107

1108

**Parameters:**

1109

1110

- `mtx` (ndarray): Matrix to initialize (not necessarily square)

1111

- `s` (Scalar): Value to assign to diagonal elements

1112

1113

**Returns:**

1114

1115

- `mtx` (ndarray): Modified matrix

1116

1117

### Random Number Generation

1118

1119

Random number generation and shuffling operations.

1120

1121

#### Set RNG Seed

1122

1123

```python { .api }

1124

cv2.setRNGSeed(seed) -> None

1125

```

1126

1127

Sets the state of the default random number generator.

1128

1129

**Parameters:**

1130

1131

- `seed` (int): New random number generator seed value

1132

1133

**Returns:**

1134

1135

- None

1136

1137

#### Uniform Random Numbers

1138

1139

```python { .api }

1140

cv2.randu(dst, low, high) -> dst

1141

```

1142

1143

Generates a uniformly distributed random numbers.

1144

1145

**Parameters:**

1146

1147

- `dst` (ndarray): Output array of random numbers (pre-allocated)

1148

- `low` (ndarray or scalar): Inclusive lower boundary of generated random numbers

1149

- `high` (ndarray or scalar): Exclusive upper boundary of generated random numbers

1150

1151

**Returns:**

1152

1153

- `dst` (ndarray): Output array filled with random numbers

1154

1155

#### Normal Random Numbers

1156

1157

```python { .api }

1158

cv2.randn(dst, mean, stddev) -> dst

1159

```

1160

1161

Fills the array with normally distributed random numbers.

1162

1163

**Parameters:**

1164

1165

- `dst` (ndarray): Output array of random numbers (pre-allocated)

1166

- `mean` (ndarray or scalar): Mean value (expectation) of the generated random numbers

1167

- `stddev` (ndarray or scalar): Standard deviation of the generated random numbers

1168

1169

**Returns:**

1170

1171

- `dst` (ndarray): Output array filled with random numbers

1172

1173

#### Random Shuffle

1174

1175

```python { .api }

1176

cv2.randShuffle(dst, iterFactor=1.0) -> dst

1177

```

1178

1179

Shuffles the array elements randomly.

1180

1181

**Parameters:**

1182

1183

- `dst` (ndarray): Input/output array to shuffle

1184

- `iterFactor` (float): Scale factor that determines the number of random swap operations

1185

1186

**Returns:**

1187

1188

- `dst` (ndarray): Shuffled array

1189

1190

### Clustering and Advanced Statistics

1191

1192

K-means clustering and advanced statistical computations.

1193

1194

#### K-Means Clustering

1195

1196

```python { .api }

1197

cv2.kmeans(data, K, bestLabels, criteria, attempts, flags) -> retval, bestLabels, centers

1198

```

1199

1200

Finds centers of clusters and groups input samples around the clusters.

1201

1202

**Parameters:**

1203

1204

- `data` (ndarray): Data for clustering (each row is a sample, floating-point type)

1205

- `K` (int): Number of clusters to split the set into

1206

- `bestLabels` (ndarray): Input/output integer array storing cluster indices for every sample

1207

- `criteria` (tuple): Termination criteria (type, max_iter, epsilon)

1208

- Type can be `cv2.TERM_CRITERIA_EPS`, `cv2.TERM_CRITERIA_MAX_ITER`, or both

1209

- `attempts` (int): Number of times the algorithm is executed with different initial labelings

1210

- `flags` (int): Flag to specify initial center selection

1211

- `cv2.KMEANS_RANDOM_CENTERS`: Random initial centers

1212

- `cv2.KMEANS_PP_CENTERS`: K-means++ center initialization

1213

- `cv2.KMEANS_USE_INITIAL_LABELS`: Use supplied bestLabels as initial labeling

1214

1215

**Returns:**

1216

1217

- `retval` (float): Compactness measure (sum of squared distances from samples to centers)

1218

- `bestLabels` (ndarray): Output integer array of labels (cluster indices)

1219

- `centers` (ndarray): Output matrix of cluster centers (one row per cluster)

1220

1221

### Fourier Transforms

1222

1223

Discrete Fourier Transform operations for frequency domain analysis.

1224

1225

#### Discrete Fourier Transform

1226

1227

```python { .api }

1228

cv2.dft(src, dst=None, flags=0, nonzeroRows=0) -> dst

1229

```

1230

1231

Performs a forward or inverse Discrete Fourier Transform of a 1D or 2D array.

1232

1233

**Parameters:**

1234

1235

- `src` (ndarray): Input array that could be real or complex

1236

- `dst` (ndarray, optional): Output array whose size and type depends on the flags

1237

- `flags` (int, optional): Transformation flags, representing a combination of DftFlags:

1238

- `cv2.DFT_INVERSE`: Perform inverse transform

1239

- `cv2.DFT_SCALE`: Scale the result

1240

- `cv2.DFT_ROWS`: Perform forward or inverse transform of every row

1241

- `cv2.DFT_COMPLEX_OUTPUT`: Output is complex array with 2 channels

1242

- `cv2.DFT_REAL_OUTPUT`: Output is real array (for inverse transform only)

1243

- `nonzeroRows` (int, optional): When not zero, the function assumes that only the first nonzeroRows rows of the input array contain non-zeros

1244

1245

**Returns:**

1246

1247

- `dst` (ndarray): Output array

1248

1249

#### Inverse Discrete Fourier Transform

1250

1251

```python { .api }

1252

cv2.idft(src, dst=None, flags=0, nonzeroRows=0) -> dst

1253

```

1254

1255

Calculates the inverse Discrete Fourier Transform of a 1D or 2D array.

1256

1257

**Parameters:**

1258

1259

- `src` (ndarray): Input floating-point real or complex array

1260

- `dst` (ndarray, optional): Output array whose size and type depend on the flags

1261

- `flags` (int, optional): Operation flags (see dft and DftFlags)

1262

- `nonzeroRows` (int, optional): Number of dst rows to process; the rest have undefined content

1263

1264

**Returns:**

1265

1266

- `dst` (ndarray): Output array. Note: idft(src, dst, flags) is equivalent to dft(src, dst, flags | DFT_INVERSE). Neither dft nor idft scales the result by default, so you should pass DFT_SCALE to one of them explicitly to make these transforms mutually inverse

1267

1268

### Image Border Operations

1269

1270

Operations for creating borders around images.

1271

1272

#### Copy and Make Border

1273

1274

```python { .api }

1275

cv2.copyMakeBorder(src, top, bottom, left, right, borderType, dst=None, value=None) -> dst

1276

```

1277

1278

Forms a border around an image.

1279

1280

**Parameters:**

1281

1282

- `src` (ndarray): Source image

1283

- `top` (int): Number of top pixels to extrapolate

1284

- `bottom` (int): Number of bottom pixels to extrapolate

1285

- `left` (int): Number of left pixels to extrapolate

1286

- `right` (int): Number of right pixels to extrapolate

1287

- `borderType` (int): Border type. See borderInterpolate for details:

1288

- `cv2.BORDER_CONSTANT`: Border filled with constant value

1289

- `cv2.BORDER_REPLICATE`: Border filled with replicated edge pixels

1290

- `cv2.BORDER_REFLECT`: Border reflects border elements

1291

- `cv2.BORDER_WRAP`: Border wraps around

1292

- `cv2.BORDER_REFLECT_101` or `cv2.BORDER_DEFAULT`: Similar to BORDER_REFLECT but with slight difference

1293

- `dst` (ndarray, optional): Destination image of the same type as src and size Size(src.cols+left+right, src.rows+top+bottom)

1294

- `value` (Scalar, optional): Border value if borderType==BORDER_CONSTANT

1295

1296

**Returns:**

1297

1298

- `dst` (ndarray): Output image with border. The function copies the source image into the middle of the destination image and fills border areas

1299