跳到正文
DEV Community· M Paracha·· 1 小時前AI 評分56

如何在 Python 中用 SSIM 衡量圖像編輯的變化幅度

Measuring how much an image edit changed with SSIM in Python

AI 導讀

這篇教學示範如何在 Python 中用 scikit-image 的 SSIM 分數和差異圖,衡量圖像編輯改變了多少及變化位置。程式以 0.15 為閾值建立遮罩,並計算變化區域的座標範圍和像素比例;文中亦列出不同 SSIM 分數的解讀。比較時應先統一圖像尺寸,並留意 JPEG 雜訊也會被計為變化;若要檢查色彩偏移,可對 RGB 陣列使用 `channel_axis=2`。

正文

M Paracha

When you retouch an image, whether you remove a stray object, clean a corner or run an upscaler, it helps to have a number that says how much the image changed and where. Eyeballing two versions side by side misses subtle smudges. The structural similarity index (SSIM) from scikit-image gives you both a score and a map of the changed areas in a few lines of Python.

Install

pip install scikit-image pillow numpy

Score and difference map

import numpy as np
from PIL import Image
from skimage.metrics import structural_similarity as ssim

def load_gray(path, size=None):
    img = Image.open(path).convert("L")
    if size:
        img = img.resize(size, Image.LANCZOS)
    return np.asarray(img, dtype=np.float64)

original = load_gray("original.png")
edited = load_gray("edited.png", size=(original.shape[1], original.shape[0]))

score, diff = ssim(original, edited, full=True, data_range=255)
print(f"SSIM: {score:.4f}")

# diff is 1.0 where the images match and lower where they differ
change = (1 - diff)
mask = (change > 0.15).astype(np.uint8) * 255
Image.fromarray(mask).save("changed_areas.png")

ys, xs = np.nonzero(mask)
if len(xs):
    print(f"changes inside box x={xs.min()}..{xs.max()}, y={ys.min()}..{ys.max()}")
    print(f"changed pixels: {len(xs) / mask.size:.2%} of the image")

Reading the numbers

SSIM What it usually means
0.99 and above Tiny, local edit; the rest of the image is untouched
0.95 to 0.99 Visible but contained changes, or light global processing
0.85 to 0.95 Noticeable global change: sharpening, colour grading, re-compression
below 0.85 A substantially different image

For a local retouch, such as removing a small object or a corner mark, you want a very high overall score and a changed-area box that sits exactly where you edited. If the mask lights up across the whole frame, the editing tool re-compressed or filtered the entire image, which is worth knowing before you publish it.

Practical notes

  • Compare at the same size. The script resizes the edited image to match the original. If an upscaler doubled the size, compare against a downscaled copy rather than stretching the original.
  • Grayscale is enough for spotting structural change. Use channel_axis=2 on RGB arrays if colour shifts matter to you.
  • JPEG noise counts as change. Save both versions as PNG before comparing, or raise the 0.15 threshold.
  • Overlay the mask on the image in any editor to see exactly what changed.

Where I use it

I run this check after cleaning up my own AI images, for example after removing the small visible Gemini mark with GGemini Watermark Remover, to confirm the edit stayed in the corner and the rest of the image is unchanged.

scikit-image SSIM docs: https://scikit-image.org/docs/stable/api/skimage.metrics.html#skimage.metrics.structural_similarity

來源:DEV Community · dev.to