Home > Blockchain >  normalize image with opencv in c ?
normalize image with opencv in c ?

Time:04-25

I have a TfLite model that takes a standardized float32 image as an input, the pixel range should convert from the [0~255] to [-1~1] I wrote a demo function but it didn't work. I couldn't set the color value back to the image; How can I set the color back to the "des" image? and Is there a better way to do that?

this is my demo code

#include <cstdint>
#include <vector>
#include <iostream>

#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/dnn.hpp>

void standardize(cv::Mat &src, cv::Mat &des)
{
    cv::Vec3b  src_color,des_color;
    for(int i = 0; i < src.rows; i  )
    {
        for(int j = 0; j < src.cols; j  )
        {
            src_color =  src.at<cv::Vec3b>(cv::Point(j,i));                        
            des_color =  des.at<cv::Vec3b>(cv::Point(j,i));
            des_color[0] = ((int) src_color[0] -127.5 ) / 127.5 ;
            des_color[1] = ((int) src_color[1] -127.5 ) / 127.5 ;
            des_color[2] = ((int) src_color[2] -127.5 ) / 127.5 ;
            
            des.at<cv::Vec3b>(cv::Point(j,i)) = des_color ;
            
            std::cout <<  (int) src_color[0]   << std::endl;                          
            std::cout << ((int) src_color[0] -127.5 ) / 127.5  << std::endl;          
            std::cout << (int) des.at<cv::Vec3b>(cv::Point(j,i))[0] << std::endl; 
        }
    }
}
int main(int argc, char *argv[])
{
    cv::Mat src, des;
    // src ---> CV_8UC3 
    src = cv::imread("/test.jpg");
    // copy to take the same size
    src.copyTo(des);
    // des ----> CV_32FC3
    src.convertTo(des, CV_32FC3);
    standardize(src,des);

    return 0;
}

CodePudding user response:

please do not write for loops. instead:

src.convertTo(dst, CV_32F);
dst -= 127;
dst /= 255; // EDIT
  • Related