我要评分
获取效率
正确性
完整性
易理解

convertTo

Usage

Converts the data type of an image to another with optional scaling. You can adjust the value range of the image by specifying the target data type and scaling factor.

Interface

1
void Mat::convertTo(OutputArray dst, int type_, double alpha, double beta) const;

Parameters

Parameter

Description

Value Range

Input/Output

dst

Output image.

Mat class

Output

type_

Target data type.

(CV_8U, CV_64F)

Input

alpha

(Optional) Scaling factor. The default value is 1.

(-inf, inf)

Input

beta

(Optional) Offset. The default value is 0.

(-inf, inf)

Input

Example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#include <opencv2/opencv.hpp>
#include <iostream>

int main() {
    // Create a 5x5 image.
    cv::Mat src = (cv::Mat_<uint8_t>(5, 5) << 0, 0, 0, 0, 0,
                                              0, 1, 1, 1, 0,
                                              0, 1, 0, 1, 0,
                                              0, 1, 1, 1, 0,
                                              0, 0, 0, 0, 0);

    // Convert the data type of the image from 8-bit unsigned integers to 32-bit floating point numbers and scale the image.
    cv::Mat dst;
    src.convertTo(dst, CV_32F);  // Data type conversion
    cv::convertScaleAbs(dst, dst, 2.0, 0); // Image scaling

    // Output image
    std::cout << dst << std::endl;

    return 0;
}

Output:

1
2
3
4
5
[[ 0  0  0  0  0]
 [ 0  2  2  2  0]
 [ 0  2  0  2  0]
 [ 0  2  2  2  0]
 [ 0  0  0  0  0]]