Lightning-AI / torchmetrics

Machine learning metrics for distributed, scalable PyTorch applications.
https://lightning.ai/docs/torchmetrics/
Apache License 2.0
2.15k stars 408 forks source link

Incorrect PSNR for uint8 images #2787

Closed ymtoo closed 1 month ago

ymtoo commented 1 month ago

🐛 Bug

PeakSignalNoiseRatio silently produces incorrect results when applied to two randomly generated uint8 images, likely due to an overflow error. However, converting the images to float32 resolves the issue and yields a reasonable PSNR value.

import torch
from torchmetrics.image import PeakSignalNoiseRatio

img1 = (torch.rand(3, 20, 30) * 255).to(torch.uint8)
img2 = (torch.rand(3, 20, 30) * 255).to(torch.uint8)
psnr = PeakSignalNoiseRatio(data_range=255.0)

psnr(img1, img2)
# tensor(27.8814)
psnr(img1.to(torch.float), img2.to(torch.float))
# tensor(7.8037)

Expected behavior

Shouldn't the function raise an error when provided with uint8 inputs?

Environment

python                    3.10.14
torchmetrics              1.4.1
torchvision               0.19.0
github-actions[bot] commented 1 month ago

Hi! thanks for your contribution!, great first issue!