Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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!

like image 986
Animesh Pandey Avatar asked Oct 08 '13 04:10

Animesh Pandey


People also ask

Where does cv2 Imwrite save the image?

When working with OpenCV Python, images are stored in numpy ndarray. To save an image to the local file system, use cv2. imwrite() function of opencv python library.

Does cv2 Imwrite overwrite Python?

imwrite will overwrite existing files without outputting an error or asking for confirmation. Image of any format can be saved using this method.

What does Imwrite return?

The imwrite() function returns the Boolean value true upon successfully writing or saving the image to the local file system.

What does cv2 Imwrite return?

imwrite() returns a boolean value. True if the image is successfully written and False if the image is not written successfully to the local path specified.


2 Answers

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

like image 173
sansuiso Avatar answered Nov 07 '22 12:11

sansuiso


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.

like image 37
it_always_ends_with_a_j Avatar answered Nov 07 '22 12:11

it_always_ends_with_a_j