简体   繁体   中英

Opencv + Python cv2.imwrite() and cv.imshow both images present different output

I am using Opencv(3.0) and Python 2.7 to do image processing, but I have an issue with cv2.imwrite() and cv2.imshow() . They produce different output, my code is as below:

tfinal = (255)*(nir_img-red_img)/(nir_img+red_img)
cv2.imwrite(_db_img1+'_NDVI'+_ext_img,tfinal)
cv2.imshow('NDVI',tfinal)

First image is output of cv2.imshow()

cv2_imshow_op

Second image is output of cv2.imwrite()

Cv2_imwrite_op

This can happen because of your data type. imwrite and imshow determine what to do with your data automatically, relaying on datatype. As said in documentation for imwrite and imshow :

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.

imshow :

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
    1. That is, the value range [0,1] is mapped to [0,255].

So, it seems that your underlying data type is not unsigned char, but float or 32-bit integer.

Also because of operation priorities you can run into troubles with:

(255)*(nir_img-red_img)/(nir_img+red_img)

You can run into overflow. It will be better to set values in range of [0; 1] and than multiply them:

(255) * ( (nir_img-red_img)/(nir_img+red_img) )

Thanks to Melnikov Sergei for a brief introduction regarding mine solution. I have resolved this using below syntax modified in my program. when I am writing my image multiplied with 255 and I'm getting the same result.

tfinal = (255)*(nir_img-red_img)/(nir_img+red_img)
cv2.imwrite(_db_img1+'_NDVI'+_ext_img,tfinal*255)
cv2.imshow('NDVI',tfinal)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM