我正在使用带深度传感器的Python模拟器进行工作。可视化是用C++完成的。传感器给出以下图像,我需要将其转换为灰度。
实现下一个结果: 如果我在Python中进行转换,我可以简单地编写:
实现下一个结果:
对于转换,我有以下公式:
normalized = (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1)
in_meters = 1000 * normalized
为了在C ++中将图像转换为灰度,我编写了以下代码:
cv::Mat ConvertRawToDepth(cv::Mat raw_image)
{
// raw_image.type() => CV_8UC3
// Extend raw image to 2 bytes per pixel
cv::Mat raw_extended = cv::Mat::Mat(raw_image.rows, raw_image.cols, CV_16UC3, raw_image.data);
// Split into channels
std::vector<cv::Mat> raw_ch(3);
cv::split(raw_image, raw_ch); // B, G, R
// Create and calculate 1 channel gray image of depth based on the formula
cv::Mat depth_gray = cv::Mat::zeros(raw_ch[0].rows, raw_ch[0].cols, CV_32FC1);
depth_gray = 1000.0 * (raw_ch[2] + raw_ch[1] * 256 + raw_ch[0] * 65536) / (16777215.0);
// Create final BGR image
cv::Mat depth_3d;
cv::cvtColor(depth_gray, depth_3d, cv::COLOR_GRAY2BGR);
return depth_3d;
}
实现下一个结果: 如果我在Python中进行转换,我可以简单地编写:
def convert_raw_to_depth(raw_image):
raw_image = raw_image[:, :, :3]
raw_image = raw_image.astype(np.float32)
# Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
depth = np.dot(raw_image, [65536.0, 256.0, 1.0])
depth /= 16777215.0 # (256.0 * 256.0 * 256.0 - 1.0)
depth *= 1000
return depth
实现下一个结果:
很明显,在Python中做得更好,但公式是相同的,图像也是相同的,那么为什么会有差异,我该如何重写C++代码以获得与Python类似的结果?
raw_image
是哪种像素格式?如果它不是每个通道16位,那么你的CV_16UC3
就没有太多意义。如果它是每个通道16位,那么你乘以256和256 x 256也没有太多意义。 - Mickaraw_image.type() => CV_8UC3
- MikeCATraw_extended
也从未被使用,因此它是无关紧要的。 - Christoph Rackwitz