dividing tuple elements with an int or float

Lie Lie.1296 at gmail.com
Sun Mar 23 13:17:56 EDT 2008


On Mar 20, 1:06 pm, royG <roygeor... at gmail.com> wrote:
> hi
> i am trying to resize some images.First i'd read the size as a 2
> tuple  and then i want to divide it by 2 or 4 or 2.5 etc..
>
> suppose
> origsz=(400,300)
> i want to divide the origsize by 2.5 so i can resize to (160,120)

There are several ways to do what you wanted:

-------------
width = origsz[0] * scale
height = origsz[1] * scale
return width, height
-------------
width, height = origsz
return width * scale, height * scale
-------------
return origsz[0] * scale, origsz[1] * scale
-------------
# and an overly complex way of doing this
return tuple(x * scale for x in origsz)
-------------


> scale=2.5
> how can i get the newsz?
> obviously origsz/2.5 won't work  ..
> thanks
> RG

Aside: I think you're a bit confused about the semantic of scaling in
image resizing, when you want to halve the image size (e.g. 100x100 ->
50x50) you scale it by 0.5, and when you want to double the image size
(e.g. 100x100 -> 200x200) you scale it by 2. This operation is done by
multiplication, not division. (i.e. scaling a 400x300 images by 2.5
means upsizing the image into 1000x750)

On Mar 20, 9:28 pm, "Jerry Hill" <malaclyp... at gmail.com> wrote:
(snip)
> That works fine for a 2-tuple, but might get unwieldy for larger
> tuples, or if you don't know the length until runtime.  A more general
> solution might use a generator expression, like this:
(snip)

I think since the semantic of origsz is well defined (width-height
pair of an image) it will always be a 2-tuple, anything other than 2-
tuple should either be discarded or raise an error (depending on
design choice).

P.S.: If you're sure that you want to use division, make sure to "from
__future__ import division" or convert the scaling factor into floats
or you'll most likely get the wrong result as Python defaults to
integer division (due to be changed in Python 3). And you should
remember that the resulting image size should also be (integer,
integer) since you can't have an image that's 100.2432x392.9875



More information about the Python-list mailing list