pyplot.imsave() saves image correctly but cv2.imwrite() saved the same image as black

为君一笑 提交于 2021-01-02 04:56:19

问题


from scipy.misc import imread
from matplotlib import pyplot

import cv2
from cv2 import cv

from SRM import SRM ## Module for Statistical Regional Segmentation

im = imread("lena.png") 
im2 = cv2.imread("lena.png")
print type(im), type(im2), im.shape, im2.shape 
## Prints <type 'numpy.ndarray'> <type 'numpy.ndarray'> (120, 120, 3) (120, 120, 3)

srm = SRM(im, 256)
segmented = srm.run()

srm2 = SRM(im2, 256)
segmented2 = srm2.run()

pic = segmented/256
pic2 = segmented2/256

pyplot.imshow(pic)
pyplot.imsave("onePic.jpg", pic)

pic = pic.astype('uint8')
cv2.imwrite("onePic2.jpg", pic2)

pyplot.show()

onePic.jpg gives the correct segmented image but onePic2.jpg gives a complete black image. Converting the datatype to uint8 using pic = pic.astype('uint8') did not help. I still gives a black image!

onePic.jpg using pyplot.imsave():

enter image description here

onePic2.jpg using cv2.imwrite():

enter image description here

Please help!


回答1:


Before converting pic to uint8, you need to multiply it by 255 to get the correct range.




回答2:


Although I agree with @sansuiso, in my case I found a possible edge case where my images were being shifted either one bit up in the scale or one bit down.

Since we're dealing with unsigned ints, a single shift means a possible underflow/overflow, and this can corrupt the whole image.

I found cv2's convertScaleAbs with an alpha value of 255.0 to yield better results.

def write_image(path, img):
    # img = img*(2**16-1)
    # img = img.astype(np.uint16)
    # img = img.astype(np.uint8)
    img = cv.convertScaleAbs(img, alpha=(255.0))
    cv.imwrite(path, img)

This answer goes into more detail.



来源:https://stackoverflow.com/questions/19239381/pyplot-imsave-saves-image-correctly-but-cv2-imwrite-saved-the-same-image-as

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!