python - python中的OpenCV mat::convertTo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16162227/
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
python - OpenCV mat::convertTo in python
提问by varagrawal
Is there any function in the OpenCV python wrapper that does the same thing as Mat's convertTo method in OpenCV 2?
OpenCV python 包装器中是否有任何函数与 OpenCV 2 中的 Mat 的 convertTo 方法做同样的事情?
I basically want to call this function in python
我基本上想在python中调用这个函数
out.convertTo( out, CV_32F, 1.0/255, 0 );
where out is a grayscale image.
其中 out 是灰度图像。
I have already made use of cv.ConvertScale by keeping my dst argument as type CV_32FC1, but I am trying to keep my python code as cv2 conformant as possible. Any clues?
我已经通过将我的 dst 参数保持为 CV_32FC1 类型来使用 cv.ConvertScale,但我试图使我的 python 代码尽可能符合 cv2。有什么线索吗?
采纳答案by Abid Rahman K
You can simply use Numpy functions for this.
为此,您可以简单地使用 Numpy 函数。
eg :
例如:
res = np.float32(out)
scaling, you will have to do separately:
缩放,你将不得不单独做:
res = res*scaling_factor
回答by knipknap
If you are not trying to convert the data type, use this:
如果您不尝试转换数据类型,请使用以下命令:
cv2.convertScaleAbs(image, result, alpha, beta)
where alpha is you scale factor and beta is a shift value. More details in the OpenCV docs.
其中 alpha 是您的比例因子,而 beta 是一个移位值。 OpenCV 文档中的更多详细信息。
回答by bfris
In the OP,
在 OP 中,
0 < multiplier < 1,
0 < 乘数 < 1,
so you don't have to worry about underflow or overflow. Solutions from Adid Rahman K and knipknap will work just fine. And they should be plenty fast.
所以你不必担心下溢或溢出。Adid Rahman K 和 knipknap 的解决方案会很好地工作。他们应该很快。
If, for any reason, you need a multiplier > 1, then you can have problems with overflow. That is, the value is not big enough to fit in the chosen data type. Most OpenCV functions will handle overflow by truncating to the max value of the data type. NumPy, though, will just "roll over" the value (e.g. for an 8 bit data type -- max value 255 -- OpenCV will force 260 to become 255, but NumPy will force 260 to 4!).
如果出于任何原因,您需要乘数 > 1,那么您可能会遇到溢出问题。也就是说,该值不足以适应所选的数据类型。大多数 OpenCV 函数将通过截断到数据类型的最大值来处理溢出。但是,NumPy 只会“翻转”该值(例如,对于 8 位数据类型——最大值 255——OpenCV 将强制 260 变为 255,但 NumPy 会强制将 260 变为 4!)。
So to process an 8 bit grayscale image and handle under/over flows do this:
因此,要处理 8 位灰度图像并处理欠流/过流,请执行以下操作:
img2 = np.int16(img1) # convert to signed 16 bit integer to allow overflow
img2 = scale_factor*img2 # apply scale factor
img2 = clip(img2, 0, 255) # force all values to be between 0 and 255
# after clip img2 is effectively unsigned 8 bit, but make it explicit:
img2 = np.uint8(img2)

