如何在OpenCV2中将float32图片写入视频文件?

时间:2019-01-16 02:06:52

标签: python opencv computer-vision

我在这里遇到一个奇怪的问题。 我从神经网络获取了输出图像,它的类型是 float32 。我添加了从互联网上拍摄的背景图片,将其从uint8转换为float32,然后将输出添加到背景图片的顶部。 现在,我想保存它,但是cv2.VideoWriter.write(blahblah)只接受 uint8 。我以为将float32转换为uint8,可能会做 * 255 ,但这可能是错误的,因为当我遇到一些奇怪的眩光时(我的图片可以在这里找到:OpenCV image shows weird glare after un-normalizing with * 255)这样做可能是由于浮点经典错误或类似性质的事情。那么,如何安全地将float32转换为uint8?或者,如何将float32写入文件?

说实话,我对某些事情感到很困惑。我知道uint8是[0,255],float32是[0,1],而且我知道cv2.videowriter.write接受uint8就是这样。在旁注中,一个解决方案似乎是从一开始就将所有内容都更改为.astype(uint8),但是我的神经网络吐出了float32,所以我必须使用它。

1 个答案:

答案 0 :(得分:1)

Float32未设置为0到1,这是您的神经网络最有可能完成的操作(softmax或sigmoid作为最后的激活函数)。要将某项设置为其他范围,可以使用以下方法:

normalized_array = (array - np.min(array))/(np.max(array) - np.min(array)) # this set the range from 0 till 1
img_array = (normalized_array * 255).astype(np.uint8) # set is to a range from 0 till 255