How can I change the depth of a cv::Mat

I have a high resolution image to do guided filtering, so I need to change the depth from CV_8UC3 to CV_32FC3 to get base layer and detail layer. However a “convertTo()” is quite expensive, I guess under the hood it always does a element wise operation. My question is, can I just change the depth of a cv::Mat, just something like “img.astype(np.float32)” from numpy.

Have you test both method?


   Mat img = imread(samples::findFile("lena.jpg"));
    float dt = 0;
    for (int i = 0; i < 100; i++)
        auto start = std::chrono::high_resolution_clock::now();
        Mat imgf;
        auto finish = std::chrono::high_resolution_clock::now();
        std::chrono::duration<double> dt0 = finish - start;
        dt += dt0.count();
    std::cout << "Elapsed time: " << dt / 100 << " s\n";


import time
import numpy as np
import cv2 as cv

img = cv.imread(cv.samples.findFile("lena.jpg"))
dt = 0
for idx in range(100):
    deb = time.perf_counter_ns()

    imgf = img.astype(np.float32)
    fin = time.perf_counter_ns()
    dt = dt + fin-deb

result c++ 0.000456 s
result python 0.000546s per call

1 Like