今天在做数据增强的时候,遇到一个奇怪的问题.调用imwite生成的图片,在本地用图片查看器打开的时候是正常的.但是在代码里imshow的时候是一片亮白.
代码类似如下

        gaussian_img = add_gaussian_noise(img_mat) #gaussian_img的数据类型是float32的
        
        new_img_name = img_name.replace(".png","gauss{}.png".format(seq))
        seq += 1
        cv2.imwrite(new_img_name, gaussian_img) #这里从本地磁盘打开这个保存的图片,看着是正常的.

        draw_box(gaussian_img,new_label_file) #这里会调用imshow('',gaussian_img)看起来就是一片亮白

上面效果类似
imwrite imshow机制

不管imwrite传入的矩阵的类型是什么样的(float32或者uint8),imwrite都会把它转换成0(black)-255(white)的整数.
https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#imwrite

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. If the format, depth or channel order is different, use Mat::convertTo() , and cvtColor() to convert it before saving

但是imshow的处理机制是不一样的,如果imshow传入的矩阵的类型是float32的话,它认为float的范围应该是0.0(black) - 1.0(white)
所以当直接imwite的时候,打开本地图片查看是正常的.但是imshow显示的图片就是一片亮白. 之前用别的方式做数据增强的时候没遇到这个问题,是因为数据类型一直用的uint8.

那如何修正这个问题呢?
imshow传入imshow('',gaussian_img/255.)而不是imshow('',gaussian_img)

那imwrite()的时候传入imwrite(gaussian_img/255.)行不行呢?答案是不行,原因前面说过了,imwrite会将其转换为0-255.gaussian_img/255的话,矩阵中的每个元素的值变成了0.0-1.0,再传入imwrite,每个元素的值都会转变为0,这样磁盘上保存下来的就是一副全黑的图像了.

相关文章:

  • 2022-12-23
  • 2021-12-08
  • 2021-09-04
  • 2021-06-02
  • 2022-12-23
  • 2021-08-18
猜你喜欢
  • 2022-12-23
  • 2021-09-26
  • 2021-06-23
  • 2021-12-20
  • 2021-07-26
  • 2022-12-23
相关资源
相似解决方案