问题:
程序需要对图像进行处理,返回的值应当是图像的ndarray数值类型。按照项目要求,需要把图像存储在固定位置下,这里打算使用Imwrite。但是保存结果一直是完全黑屏图片。
效果如下,左边是imshow的结果,右边是imwrite的结果。
解决方法:
在imwritre和imshow两个调用前,增加语句如下
out_img = (out_img * 255).astype(np.uint8)
原理:
代码如下,按道理out_img一直没变,imshow和imwrite的结果应当是相同的。
cv2.imwrite("out.png", out_img)
cv2.namedWindow("out", 0);
cv2.resizeWindow("out", 640, 480);
cv2.imshow("out",out_img)
查询后,用自己的话转述一下,图像数据处理后得到的数据,可能读取、处理形式对于两个函数是不一样的,正常情况下直接读取图片,显示图片、保存图片的图片数据均为整型
直接输出out_img的结果如下,显然不是整型
文档中对于两个方法的描述如下,
imwrite:
imshow:The function imwrite saves the image to the specified file. The image format is chosen based on the filename extension (see imread() for the list of extensions). Only 8-bit (or 16-bit unsigned (CV_16U) in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images can be saved using this function.
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].
可以看到此时的imshow会对图像的数据进行[0,255]的映射,所以imshow可以正常输出,而此时的imwrite不可以
所以需要将数据转换为[0,255],再交给两个函数,他们才能进行正确操作,效果如下,问题解决。