我尝试在 python 中实现以下 C++ 代码:
depth.convertTo(depth, CV_64FC1); // I do not know why it is needed to be
transformed to 64bit image my input is 32bit
Mat nor(depth.size(), CV_64FC3);
for(int x = 1; x < depth.cols - 1; ++x)
{
for(int y = 1; y < depth.rows - 1; ++y)
{
Vec3d t(x,y-1,depth.at<double>(y-1, x)/*depth(y-1,x)*/);
Vec3d l(x-1,y,depth.at<double>(y, x-1)/*depth(y,x-1)*/);
Vec3d c(x,y,depth.at<double>(y, x)/*depth(y,x)*/);
Vec3d d = (l-c).cross(t-c);
Vec3d n = normalize(d);
nor.at<Vec3d>(y,x) = n;
}
}
imshow("normals", nor);
Python 代码:
d_im = cv2.imread("depth.jpg")
d_im = d_im.astype("float64")
normals = np.array(d_im, dtype="float32")
h,w,d = d_im.shape
for i in range(1,w-1):
for j in range(1,h-1):
t = np.array([i,j-1,d_im[j-1,i,0]],dtype="float64")
f = np.array([i-1,j,d_im[j,i-1,0]],dtype="float64")
c = np.array([i,j,d_im[j,i,0]] , dtype = "float64")
d = np.cross(f-c,t-c)
n = d / np.sqrt((np.sum(d**2)))
normals[j,i,:] = n
cv2.imwrite("normal.jpg",normals*255)
输入图像:
C++ 代码输出:
我的Python代码输出:
我找不到这些差异的原因。我如何使用 python 获得 C++ 代码输出?
最佳答案
正如user8408080所说,您的输出似乎存在由jpeg格式引起的伪影。另请记住,导入 8 位图像作为深度图不会得到与直接使用深度图矩阵相同的结果。
关于你的Python代码,我的建议是使用向量化函数并尽可能避免循环(它非常慢)。
zy, zx = np.gradient(d_im)
# You may also consider using Sobel to get a joint Gaussian smoothing and differentation
# to reduce noise
#zx = cv2.Sobel(d_im, cv2.CV_64F, 1, 0, ksize=5)
#zy = cv2.Sobel(d_im, cv2.CV_64F, 0, 1, ksize=5)
normal = np.dstack((-zx, -zy, np.ones_like(d_im)))
n = np.linalg.norm(normal, axis=2)
normal[:, :, 0] /= n
normal[:, :, 1] /= n
normal[:, :, 2] /= n
# offset and rescale values to be in 0-255
normal += 1
normal /= 2
normal *= 255
cv2.imwrite("normal.png", normal[:, :, ::-1])
关于python - python中深度图的表面法线计算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53350391/