OpenCV中imshow()与imwrite()输出不同问题

正文索引 [隐藏]

还是使用之前的MultiNet测试,输出图像发现图像丢失了

问题

图像在经过卷积之后,使用imshow以及imwrite会出现不同结果 如下:

imshow结果,大部分图像丢失

imwrite结果
[](http://47.93.7.151/wp-content/uploads/2019/07/um_000044_out.png

分析问题

我们查看官方文档发现imshow如下解释:

The function imshow displays an image in the specified window. If the window was created with the CV_WINDOW_AUTOSIZE flag, the image is shown with its original size. Otherwise, the image is scaled to fit the window. The function may scale the image, depending on its depth:
        If the image is 8-bit unsigned, it is displayed as is.
        If the image is 16-bit unsigned or 32-bit integer, the pixels are divided by 256. That is, the value range [0,255*256] is mapped to [0,255].
        If the image is 32-bit floating-point, the pixel values are multiplied by 255. That is, the value range [0,1] is mapped to [0,255].

opencv中imshow内部的参数类型可以分为两种。(1)当输入矩阵是uint8类型的时候,此时imshow显示图像的时候,会认为输入矩阵的范围在0-255之间。(2)如果imshow的参数是double类型的时候,那么imshow会认为输入矩阵的范围在0-1。

解决方案

1.用OpenCV中imread输入照片后是一个数组对象,在进行一系列的对数组操作后数组已经变成了float类型,之后再对数组进行imshow时即出现上面的第二种情况。倘若图像矩阵(double型)的矩阵元素不在0-1之间,那么imshow会把超过1的元素都显示为白色,即255。因为double的矩阵并不是归一化后的矩阵并不能保证元素范围一定就在0-1之间。
所以在imshow前面将数据float格式转换成uint8格式:

image_out  = image.astype(np.unint8)

2.在输出图像之前进行归一化操作,使图像数值范围在0-1之间

image /=255