我创建并查看随机图像。然后,此图像使用opencv编码为jpg文件。但是,在解码此图像后,颜色已略有变化。使用png进行编码无法看到此行为。谁能解释为什么会这样?是jpeg压缩的负面结果吗?难道我做错了什么?下面的代码示例来重新创建它。
import cv2
import numpy as np
random_image = np.random.randint(255, size=(4,4,3), dtype=np.uint8)
cv2.imshow('Image', random_image)
cv2.waitKey()
_, img_encoded = cv2.imencode('.jpg', random_image)
img_string = img_encoded.tostring()
npimg = np.fromstring(img_string, dtype=np.uint8)
img = cv2.imdecode(npimg, 1)
cv2.imshow('Image', img)
cv2.waitKey()
# Does not happen with png
_, img_encoded = cv2.imencode('.png', random_image)
img_string = img_encoded.tostring()
npimg = np.fromstring(img_string, dtype=np.uint8)
img = cv2.imdecode(npimg, 1)
cv2.imshow('Image', img)
cv2.waitKey()
编辑以添加一些4x4图像。原版的:
JPG格式
PNG
再次编辑512x512图片
Original 512x512
JPG 512x512
PNG 512x512
最佳答案
JPG
是有损压缩。实际上,它通过以对眼睛“无害”的方式修改颜色来起作用。 PNG
是一种无损压缩,因此您可以在编码/解码后获得确切的压缩效果。
通过指定JPG
参数,您可以控制有多少IMWRITE_JPEG_QUALITY
可以自由修改图像:
cv2.imencode(('.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 90])
较高的值表示较少的压缩,结果更接近原始。例如,100
应该完全没有压缩,并且结果与原始结果相同。
关于python - 为什么cv2.imencode ('jpg',…)似乎改变了图像的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64342838/