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()
:
onePic2.jpg using cv2.imwrite()
:
Please help!
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.
imwrite will overwrite existing files without outputting an error or asking for confirmation. Image of any format can be saved using this method.
The imwrite() function returns the Boolean value true upon successfully writing or saving the image to the local file system.
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.
Before converting pic
to uint8
, you need to multiply it by 255 to get the correct range.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With