大师网-带你快速走向大师之路 解决你在学习过程中的疑惑,带你快速进入大师之门。节省时间,提升效率

OpenCV cv2.imshow和cv2.imwrite结果不一致

简述

本节将针对使用OpenCVcv2.imshowcv2.imwrite结果不一致问题进行小结

问题复现过程

#图片路径
sta = './Sketch/o5MuJ5T0Z0uQLT-z883VQsmx1bSA/15438410304182994.jpg'
#使用模型
net = cv2.dnn.readNetFromTorch('models/eccv16/composition_vii.t7')
image = cv2.imread(sta)
image = imutils.resize(image, width=600)
(h, w) = image.shape[:2]

blob = cv2.dnn.blobFromImage(image, 1.0, (w, h),
    (103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()

output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
output /= 255.0
output = output.transpose(1, 2, 0)
#窗体显示
cv2.imshow("output", output)
cv2.waitKey(0)
#保存本地
cv2.imwrite('output.png', output)
原始图片

imshow窗体预览

imwrite本地保存

解决过程

1、测试图片进行常规操作imshowimwrite是否有区别,测试发现无明显区别
2、检索是否有类似问题,是否两方法实现原理不同,后与stackoverflow发现有类似问题
stackoverflow.com相关链接:cv2.imshow and cv2.imwrite

答案中描述二者区别

测试修改对比

#图片路径
sta = './Sketch/o5MuJ5T0Z0uQLT-z883VQsmx1bSA/15438410304182994.jpg'
#使用模型
net = cv2.dnn.readNetFromTorch('models/eccv16/composition_vii.t7')
image = cv2.imread(sta)
image = imutils.resize(image, width=600)
(h, w) = image.shape[:2]

blob = cv2.dnn.blobFromImage(image, 1.0, (w, h),
    (103.939, 116.779, 123.680), swapRB=False, crop=False)
net.setInput(blob)
output = net.forward()

output = output.reshape((3, output.shape[2], output.shape[3]))
output[0] += 103.939
output[1] += 116.779
output[2] += 123.680
# 由于imshow、imwrite两个函数的范围期望不同,使用imshow需除以255,imwrite则不需要
# output /= 255.0
output = output.transpose(1, 2, 0)
#窗体显示
cv2.imshow("output", output)
cv2.waitKey(0)
#保存本地
cv2.imwrite('output.png', output)
注释后imshow窗体预览

注视后imwrite本地保存