Error when splitting image in half using Python



  • I'm trying to split an image in half using the code below, but I'm having a return error.

    Code:

    import cv2
    import numpy as np
    

    Read the image

    img = cv2.imread("IMD015.png")
    width = img.shape

    Cut the image in half

    width_cutoff = width / 2
    s1 = img[:, width_cutoff]
    s2 = img[:, width_cutoff:]

    Save each half

    cv2.imsave("face1.png", s1)
    cv2.imsave("face2.png", s2)

    i1 = cv2.imread("face1.png")
    i2 = cv2.imread("face2.png")
    assert i1.mode == i2.mode, "Different kinds of images."
    assert i1.size == i2.size, "Different sizes."

    pairs = zip(i1.getdata(), i2.getdata())
    if len(i1.getbands()) == 1:
    # for gray-scale jpegs
    dif = sum(abs(p1-p2) for p1,p2 in pairs)
    else:
    dif = sum(abs(c1-c2) for p1,p2 in pairs for c1,c2 in zip(p1,p2))

    ncomponents = i1.size[0] * i1.size[1] * 3
    print ("Difference (percentage):"+ str((dif / 255.0 * 100) / ncomponents))

    Error:

    line 10, in <module>
    width_cutoff = width / 2
    TypeError: unsupported operand type(s) for /: 'tuple' and 'int'

    I know the mistake is in the division, but how do I make it right?



  • The error is very descriptive, you are taking a tuple and trying to split by 2. You can only split a number, not a dataset.

    The documentation is quite flawed, but in the end I managed to find that the variable img.shape is getting even a tuple with some image data. You can't take that tuple, but you can deconstruct it into variables and then take one of these variables and make the split if any of the elements is a number, and in fact I managed to infer it is. So to get the width should have done this:

    _, width, _ = img.shape
    

    https://github.com/maniero/SOpt/blob/master/Python/Syntax/MultiAssign.py .

    Even if I don't need the other elements I need to pick them up, in case I used _ to discard them and not to create a variable to the log.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2