Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cv2.imshow and cv2.imwrite

Tags:

python

opencv

Can someone explain why the OpenCV imshow and imwrite function seem to result in a completely different image?

The first picture corresponds to imshow and the second picture corresponds to imwrite. Result is an array of floating point values between 0 and 255.

**result = result.astype(np.uint8)**
cv2.imshow('img', result)
cv2.imwrite('img.png', result)

TargetResult

like image 838
Matthias Avatar asked Mar 18 '14 19:03

Matthias


2 Answers

I used the following (c++) code with OpenCV 2.4.8:

cv::Mat_<float> img(300,300);
cv::theRNG().fill(img,cv::RNG::UNIFORM,0,255);
cv::imshow("Img",img);
cv::waitKey();
cv::imwrite("test.png",img);

and it results in the following images:

enter image description here

with imshow.

enter image description here

with imwrite.

This is due to the different range expectation of the two functions, imwrite always expects [0,255], whereas imshow expects [0,1] for floating point and [0,255] for unsigned chars.

In order to display the correct output with imshow, you need to reduce the range of your floating point image from [0,255] to [0,1]. You can do this using convertTo and an appropriate scaling factor, or simply by dividing your image by 255.

like image 54
BConic Avatar answered Nov 11 '22 19:11

BConic


since you are using python this might help :

def showimg(img):
    cv2.namedWindow("test", cv2.WINDOW_NORMAL)
    img = np.array(img,dtype=float)/float(255)
    cv2.imshow('test',img)
    cv2.resizeWindow('test',600,600)
    cv2.waitKey(0)
like image 2
samer226047 Avatar answered Nov 11 '22 19:11

samer226047