how to define a function with inputted image as parameter?

Question:

I’m very new to python, so please bear with me. I have an assignment for which I have to make a function that crops an inputted image, however I can’t get the function to recognize the input as an image, and the im.shape call isn’t working.

EDIT: changed a bunch, having the function recognize the input as a string, and a tuple out of range error

This is what I have for the function:

def make_square(im):
    h = im.size[0]
    w = im.size[1]
    if w > h:
        w = w - (h-w)
    elif h > w: 
        h = h - (w-h)
    im = im.crop((w, h))
    print(im)

and this is what I have when I call it:

from PIL import Image
from check2_helper import make_square

im1 = Image.open('ca.jpg')
imsquare = make_square(im1)
imsquare.show()

Any help would be greatly appreciated!

Asked By: em_

||

Answers:

size() returns (width, height) tuple, and crop() takes a (left, top, right, bottom) tuple.

If you want to pass the cropped image back from the function, then you have to return it.

This works for me:

from PIL import Image

def make_square(im):
    print(im.size)
    w, h = im.size
    d = min(w, h)
    x = (w-d)/2
    y = (h-d)/2
    im = im.crop((x, y, d+x, d+y))
    print(im)
    return im

image = Image.open('ca.jpg')
imsquare = make_square(image)
imsquare.show()
Answered By: DobbyTheElf

There are a few issues in your code.

Firstly, you open the image twice – image = Image.open('ca.jpg'), and then inside your function in im = Image.open(im). You only need either one of those.

Secondly, crop method expects a tuple with four values, defining the left, upper, right, and lower pixel coordinate of the rectagular region the image will be cropped to. Your tuple has only two values.

Third, your function doesn’t return anything. Instead of print(im), you need to add return im. That way, in imsquare = make_square(im1) you assign the result of your function to imsquare.

With that you will be able to run your code. With that being said I don’t think your cropping method is right. I am not exactly sure what cropping method you want, but here is how I would do it: After comparing w and h I’d assign the smaller value to a new variable:

if w > h: s=h
else: s=w
im = im.crop((0, 0, s, s))
return im
Answered By: idiot
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.