How to Compute Structural Similarity Index (SSIM) in Python?

Estimated read time 2 min read

To compute the Structural Similarity Index (SSIM) in Python, you can use the scikit-image library, which provides a convenient function for SSIM calculation. Here’s an example:

from skimage.metrics import structural_similarity as ssim
import cv2

# Load two images
image1 = cv2.imread("image1.jpg", cv2.IMREAD_GRAYSCALE)
image2 = cv2.imread("image2.jpg", cv2.IMREAD_GRAYSCALE)

# Compute SSIM
ssim_score = ssim(image1, image2)

print("SSIM score:", ssim_score)

In this example, we import the structural_similarity function from skimage.metrics module, which is used for computing the SSIM. We also import the cv2 module from OpenCV to read the images.

You need to provide the paths or filenames of the two images you want to compare. The images are loaded using cv2.imread() function, specifying the grayscale mode (cv2.IMREAD_GRAYSCALE) to convert the images to grayscale.

The ssim() function takes the two grayscale images as inputs and computes the SSIM score. The resulting SSIM score is stored in the ssim_score variable and printed.

Make sure to have scikit-image and OpenCV installed (pip install scikit-image opencv-python) before running this code. Adjust the filenames and paths to match your specific image files.

Note that SSIM is typically used for comparing image similarity and quality assessment. It works best with grayscale images, but you can also use it with color images by converting them to the appropriate color space, such as converting RGB to YUV or converting to grayscale before calculating SSIM.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply