我目前正在尝试使用OpenCV在C ++中翻译Python图像检测算法(以便在智能手机应用程序中使用它)。 我在某一点上得到了类似的结果,其中两种算法似乎因图像中的小差异的积累而分歧:我正在对图像应用一些变换,但Python中的十进制数字比C ++中的小数字要大得多(我使用CV_64FC1矩阵),所以在一些迭代后我得到越来越多不同的结果......
您对如何克服这个问题有任何想法吗?
提前致谢:)
编辑:这是一个在Python和C ++中提供不同结果的代码
void conv2(const Mat &img, const Mat& kernel, Mat& dest) {
Mat source = img;
Point anchor(kernel.cols - kernel.cols/2 - 1, kernel.rows - kernel.rows/2 - 1);
flip(kernel, kernel, 0);
filter2D(source, dest, -1, kernel, anchor);
}
void myFunc() {
Mat im = imread("3.png", IMREAD_GRAYSCALE);
im.convertTo(im, CV_64F);
int rows = im.rows;
int cols = im.cols;
int sze = 7;
Mat gauss = getGaussianKernel(sze, 1);
Mat f = gauss * gauss.t();
Mat fx, fy;
Sobel(f, fx, -1, 1, 0);
Sobel(f, fy, -1, 0, 1);
Mat Gx, Gy, Gxx, Gyy, Gxy;
filter2D(im, Gx, -1, fx);
filter2D(im, Gy, -1, fy);
pow(Gx, 2, Gxx);
pow(Gy, 2, Gyy);
Gxy = Gx.mul(Gy);
gauss = getGaussianKernel(sze, 38);
f = gauss * gauss.t();
conv2(Gxx, f, Gxx);
conv2(Gyy, f, Gyy);
conv2(Gxy, f, Gxy);
Gxy *= 2;
Mat Gxx_minus_Gyy = Gxx - Gyy;
Mat Gxy_squared, Gxx_minus_Gyy_squared;
pow(Gxy, 2, Gxy_squared);
pow(Gxx_minus_Gyy, 2, Gxx_minus_Gyy_squared);
Mat denom;
sqrt(Gxy_squared + Gxx_minus_Gyy_squared, denom);
// denom += numeric_limits<double>::epsilon();
Mat sin2theta = Gxy / denom;
cout.precision(dbl::max_digits10);
cout << fixed << sum(sin2theta) << endl;
exit(1);
}
和Python:
def conv2(img, kernel):
source = img
kernel = cv2.flip(kernel, 0)
rows, cols = kernel.shape
anchor = (int(cols - cols/2 - 1), int(rows - rows/2 - 1))
return cv2.filter2D(source, -1, kernel, anchor=anchor)
def myFunc():
im = cv2.imread('3.png', cv2.IMREAD_GRAYSCALE)
im = np.float64(im)
rows, cols = im.shape;
sze = 7
gauss = cv2.getGaussianKernel(sze, 1);
f = gauss * gauss.T;
fx = cv2.Sobel(f, -1, 1, 0)
fy = cv2.Sobel(f, -1, 0, 1)
Gx = cv2.filter2D(im, -1, fx)
Gy = cv2.filter2D(im, -1, fy)
Gxx = cv2.pow(Gx,2);
Gyy = cv2.pow(Gy,2);
Gxy = cv2.multiply(Gx, Gy);
gauss = cv2.getGaussianKernel(sze, 38);
f = gauss * gauss.T;
Gxx = conv2(Gxx, f)
Gyy = conv2(Gyy, f)
Gxy = 2*conv2(Gxy, f)
Gxx_minus_Gyy = Gxx - Gyy
Gxy_squared = cv2.pow(Gxy, 2)
Gxx_minus_Gyy_squared = cv2.pow(Gxx_minus_Gyy, 2)
denom = cv2.sqrt(Gxy_squared + Gxx_minus_Gyy_squared)
# denom += np.finfo(float).eps;
sin2theta = Gxy/denom
print(cv2.sumElems(sin2theta))
exit()
对myFunc()的调用打印出“sin2theta”矩阵中元素的总和:Python给出86587.44928456949,C ++给出86825.05505451805947814,这开始产生非常重要的区别。