I found an interesting issue with different results of SVD (Singular Value Decomposition) in my project. I need to find intersections by lines (4 points). I have 2 vertical lines and 2 horizontal lines.
I wrote the following code for Python, and it works correctly:
a = numpy.array([
[0.99773484, -0.06726905],
[0.02908471, 0.9995769]
])
b = numpy.array([
[180.0],
[264.66666]
])
_, (x0, y0) = cv2.solve(a, b, flags=cv2.DECOMP_SVD)
# x0 = 197.87232204
# y0 = 259.02119276
Also I wrote the same code using Kotlin, and it works correctly, too:
val a = Mat.zeros(2, 2, CvType.CV_32F)
a.put(0, 0, 0.99773484)
a.put(0, 1, -0.06726905)
a.put(1, 0, 0.02908471)
a.put(1, 1, 0.9995769)
val b = Mat.zeros(2, 1, CvType.CV_32F)
b.put(0, 0, 180.0)
b.put(1, 0, 264.66666)
val linearFit = Mat()
Core.solve(a, b, linearFit, Core.DECOMP_SVD)
val x0 = linearFit.get(0, 0)[0]
val y0 = linearFit.get(1, 0)[0]
// x0 = 197.87232971191406
// y0 = 259.02117919921875
But when I wrote this code using C++, I got different results:
cv::Mat a = cv::Mat::zeros(2, 2, CV_32F);
a.at<float>(0, 0) = 0.99773484;
a.at<float>(0, 1) = -0.06726905;
a.at<float>(1, 0) = 0.02908471;
a.at<float>(1, 1) = 0.9995769;
cv::Mat b = cv::Mat::zeros(2, 1, CV_32F);
b.at<float>(0, 0) = 180.0;
b.at<float>(1, 0) = 264.66666;
cv::Mat linearFit;
cv::solve(a, b, linearFit, cv::DECOMP_SVD);
double x0 = linearFit.at<cv::Vec3b>(0, 0)[0];
double y0 = linearFit.at<cv::Vec3b>(1, 0)[0];
// x0 = 81.000000
// y0 = 182.000000
Is this a problem with my syntax or with opencv2.framework for iOS? I tested on opencv2.framework v.3.4.19 and v.4.1.0.
P.S. The function to find intersections I got in this answer: https://stackoverflow.com/a/46572063
Type issue.
Vec3b
means three values of uint8_t
.
cv::solve()
likely returned float
(CV_32F
) values. It might have returned CV_32FC1
, i.e. single-channel, or CV_32FC3
, i.e. three-channel.
You might have to use Vec3f
, if the resulting Mat is 3-channel. If not, float
would be correct.
If it's not a 32-bit float, different types might be required. CV_64F
is a possibility.