功能需求:实现对深度图像空洞值(深度值为0)和非空洞二值化掩膜。
深度图:
二值化掩膜图:
编程注意事项:
1.正确读取深度图像(尤其是格式(参数:flags),深度图读取格式为-1)
2.图像的size(rows,cols),行列顺序不能反,记忆:行列式子所以是先行后列
参考教程:C++ OpenCV学习:一、读入图片,显示图片,保存图片_c++保存图片-CSDN博客
C++代码:
#include <opencv2/opencv.hpp>
#include <opencv2/highgui/highgui_c.h>
using namespace cv;
Mat mask_hole(Mat& depth)
{
Mat mask = Mat::ones(depth.rows,depth.cols, depth.type());
for (int i = 0; i < depth.rows; i++)
{
for (int j = 0; j < depth.cols; j++)
{
if (depth.at<uchar>(i, j) == 0)
{
mask.at <uchar>(i,j) = 0;
}
else
{
mask.at <uchar>(i, j) = 255;
}
}
}
return mask;
}
string matpath = "../Art/disp5.png";
Mat depthraw = imread(matpath, -1);//-1或0都没问题
Mat mask = mask_hole(depthraw);
imwrite("mask_depth.png", mask);
python代码:
import cv2
import numpy as np
import os
#cv_imread可读取中文路径版
def cv_imread(file_path) :
cv_img = cv2.imdecode(np.fromfile(file_path, dtype = np.uint8), -1)
return cv_img
depth_image_file r"..标准数据集\Art"
depth_image = cv_imread(depth_image_file)
mask = np.where(depth_image > 0, 255, 0).astype(np.uint8)
cv2.imshow("Mask", mask)
mask_filename = os.path.splitext(os.path.basename(depth_image_file))[0] # 去掉文件扩展名
cv2.imwrite(f"mask{mask_filename}.png",mask)
错误情况: