Get same results in C++ and python code

Hi,

I translate python code in C++. I check result in python and c++ and sometimes it’s difficult to get same result. example python code

import numpy as np
import cv2 as cv

xf = np.array([38.4, 40.7])
xi =  xf.astype(np.int32)
print(xi)

result is

[38 40]

Now in C++

    Mat xf = (Mat_<float>(2, 1) << 38.4, 40.7);
    Mat xi;
    xf.convertTo(xi, CV_32S);
    cout << "Mat float : " << xf << endl;
    cout << "Mat int : " << xi << endl;

and result is

Mat float : [38.400002;
40.700001]
Mat int : [38;
41]

Ok that’s just a difference of 1. But if data is a top point in a rectangle and use it to extract an image for a deep learning model, inference results are really different

This post is only a warning

that truncates. it’s literally a double to int32 cast (double because python float literals are double and np.array respects that). such a cast, by whatever requirements (CPU architecture, whatever, I don’t care), is a truncation. numpy is striving to be very predictable with these things.

that does some math in the background. probably even saturating math. OpenCV does “stuff”.

always think about your numerical conversions, decide what behavior you want, and make sure it’s done explicitly.

that sounds ominous

It is like

cap.open(samples::findFile("lena.jpg"));
cap >> img;

and
img=imread(samples::findFile("lena.jpg"));

img are not equal (on windows)

and again for inference results will not be equal with same data file

excuse me, why do you try to treat a jpeg image as if it were a video file?

I know you to be generally competent. lapses in mental capacity and communication abilities could indicate a stroke. I’m being serious. please make sure you’re okay.

May be it is a new pandemic

1 Like

I am very surprised that VideoCapture tolerates this. the CV_IMAGES backend seems to be responsible for this succeeding.

either way, I would not expect results to be exactly the same for VideoCapture() and imread()