Matthias
Matthias

Reputation: 4677

cv2.imshow and cv2.imwrite

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)

Target Result

Upvotes: 8

Views: 21592

Answers (2)

samer226047
samer226047

Reputation: 125

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)

Upvotes: 2

BConic
BConic

Reputation: 8980

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.

Upvotes: 14

Related Questions