C++ 将 16 位深度的 CvMat* 转换为 8 位深度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6909464/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert 16-bit-depth CvMat* to 8-bit-depth
提问by Sirnino
I'm working with Kinect and OpenCV. I already search in this forum but I didn't find anything like my problem. I keep the raw depth data from Kinect (16 bit), I store it in a CvMat* and then I pass it to the cvGetImage to create an IplImage* from it:
我正在使用 Kinect 和 OpenCV。我已经在这个论坛中搜索过,但我没有发现任何类似我的问题。我保留来自 Kinect(16 位)的原始深度数据,将其存储在 CvMat* 中,然后将其传递给 cvGetImage 以从中创建 IplImage*:
CvMat* depthMetersMat = cvCreateMat( 480, 640, CV_16UC1 );
[...]
cvGetImage(depthMetersMat,temp);
But now I need to work on this image in order to do cvThreshdold and find contours. These 2 functions need an 8-bit-depth-image in input. How can I convert the CvMat* depthMetersMat in an 8-bit-depth-CvMat* ?
但是现在我需要处理这个图像以执行 cvThreshdold 并找到轮廓。这两个函数在输入中需要一个 8 位深度的图像。如何将 CvMat* depthMetersMat 转换为 8-bit-depth-CvMat* ?
回答by Gillfish
The answer that @SSteve gave almost did the trick for me, but the call to convertTo
seemed to just chop off the high order byte instead of actually scaling the values to an 8-bit range. Since @Sirnino didn't specify which behavior was wanted, I thought I'd post the code that will do the (linear) scaling, in case anyone else is wanting to do that.
@SSteve 给出的答案几乎对我有用,但调用convertTo
似乎只是切断了高位字节,而不是实际将值缩放到 8 位范围。由于@Sirnino 没有指定需要哪种行为,我想我会发布将执行(线性)缩放的代码,以防其他人想要这样做。
SSteve's original code:
SSteve 的原始代码:
CvMat* depthMetersMat = cvCreateMat( 480, 640, CV_16UC1 );
cv::Mat m2(depthMetersMat, true);
m2.convertTo(m2, CV_8U);
To scale the values, you just need to add the scale factor (1/256, or 0.00390625, for 16-bit to 8-bit scaling) as the third parameter (alpha) to the call to convertTo
要缩放值,您只需将缩放因子(1/256,或 0.00390625,用于 16 位到 8 位缩放)作为第三个参数 (alpha) 添加到调用 convertTo
m2.convertTo(m2, CV_8U, 0.00390625);
You can also add a fourth parameter (delta) that will be added to each value after it is multiplied by alpha. See the docsfor more info.
您还可以添加第四个参数 (delta),该参数将在乘以 alpha 后添加到每个值。有关更多信息,请参阅文档。
回答by SSteve
This should work:
这应该有效:
CvMat* depthMetersMat = cvCreateMat( 480, 640, CV_16UC1 );
cv::Mat m2(depthMetersMat, true);
m2.convertTo(m2, CV_8U);
But according to the OpenCV docs, CvMat is obsolete. You should use Mat instead.
但是根据 OpenCV 文档,CvMat 已经过时了。您应该改用 Mat。