简体   繁体   English

在c ++中的opencv convertTo和Python中的手动转换之间有不同的结果

[英]different result between opencv convertTo in c++ and manual conversion in Python

I'm trying to port a code from c++ to python, where at some point a frame is extracted from a .oni recording (OpenNI2), scaled to 8 bit and saved as jpg. 我正在尝试将代码从c ++移植到python,在某些时候从.oni录制文件(OpenNI2)中提取一帧,缩放为8位并另存为jpg。 I use OpenCV function convertTo in c++, which is not available in python, so reading the documentation I'm triying to do the same operation manually, but something is wrong. 我在c ++中使用OpenCV函数convertTo,但在python中不可用,因此我正在尝试阅读文档以手动进行相同的操作,但是出了点问题。

This is the c++ 这是C ++

cv::Mat depthImage8;

double maxVal = 650.0;
double minVal = 520.0;
depthImage.convertTo(depthImage8, CV_8UC1,  255.0/(maxVal - minVal), -minVal * 255.0/(maxVal - minVal));
cv::imwrite(dst_folder + "/" + std::to_string(DepthFrameIndex) + "_8bit.jpg", depthImage8);

which produce: 产生:

在此处输入图片说明

This is the Python version: 这是Python版本:

depth_scale_factor = 255.0 / (650.0-520.0)
depth_scale_beta_factor = -520.0*255.0/(650.0-520.0)
depth_uint8 = (depth_array*depth_scale_factor+depth_scale_beta_factor).astype('uint8')

which produce: 产生:

在此处输入图片说明

This code seems to work, but however images generated are different, while the original one (16UC1) are identical (already checked and they match pixel by pixel), so there should be something wrong in the conversion functions. 该代码似乎有效,但是生成的图像不同,而原始图像(16UC1)是相同的(已检查并且它们逐像素匹配),因此转换函数中应该有问题。

Thanks to the comments I came up with the solution. 多亏了这些评论,我才提出了解决方案。 As stated by users michelson and Dan Masek Opencv performs saturate_cast operation, while numpy don't. 正如用户所说,michelson和Dan Masek Opencv执行saturate_cast操作,而numpy不执行。 So in order to get the same result, Python version must be: 因此,为了获得相同的结果,Python版本必须为:

    depth_uint8 = depth_array*depth_scale_factor+depth_scale_beta_factor
    depth_uint8[depth_uint8>255] = 255
    depth_uint8[depth_uint8<0] = 0
    depth_uint8 = depth_uint8.astype('uint8')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM