[Python] How can I calculate SSIM between 2 images using scikit-image?

Discussão em 'Python' iniciado por Stack, Abril 2, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to find the SSIM between two images that I'm storing using the Image data structure from PIL. the structural_similarity function requires both images to be stored as numpy arrays of the same shape, but despite me supplying such arrays, I keep getting an error suggesting they are not in fact the same shape.

    The error I keep getting comes from the structural_similarity function, with the error being:

    operands could not be broadcast together with shapes (3,) (2,)


    My code looks as follows:

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

    def readAndResize(image_path, width=60, height=30):
    try:
    image = Image.open(image_path)
    image = image.resize((width, height))
    return image
    except:
    print("Error: Could not read the image at", image_path)
    return []

    def computeMeasure1(image1, image2):
    img1 = np.asarray(image1)
    img2 = np.asarray(image2)
    print(img1.shape) # prints (30, 60, 3)
    print(img2.shape) # prints (30, 60, 3)
    measure_value = structural_similarity(img1, img2, win_size=(3,3), multichannel=True)
    return measure_value

    def main():

    path = "Images/Student_Test/generated.photos_v3_0228313.jpg"
    path2 = "Images/Student_Train/6_img_1553496386570.jpg"

    image = (readAndResize(path))
    image2 = (readAndResize(path2))

    print(computeMeasure1(image,image2))

    main()


    I have tried to store the images using imread() from opencv-python, but the exact same problem persisted, with the same error popping up despite both arrays being the same shape.

    Continue reading...

Compartilhe esta Página