gpt4 book ai didi

python - python中深度图的表面法线计算

转载 作者:太空宇宙 更新时间:2023-11-03 21:24:28 39 4
gpt4 key购买 nike

我尝试在 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)

输入图像:

enter image description here

C++代码输出:

enter image description here

我的 python 代码输出:

enter image description here

我找不到这些差异的原因。我如何使用 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/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com