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

标签 python opencv normals

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

相关文章:

python - 无法在 pybind11 中绑定(bind)重载的静态成员函数

python - 如何根据值订购字典?

c++ - OpenCV C++中的微小星球全景图

opengl - GLSL 中的正常旋转

c++ - 立方体的法线似乎指向内部

计算多边形的 OpenGL 面法线

python - 如何使用 Tweepy 创建 Pandas 数据框?

python - 在 Pandas 中操作数据框的数据

Python3并行处理opencv视频帧

opencv - 使用CUDA编译的OpenCV支持是否可以在没有CUDA的情况下使用?