Wand crop() function in Python
Cropping an image refers to select an area of image and discard everything outside the cropped area. Crop tool is an important tool as it allows us to get the only relevant part of an image. Also sometimes something unwanted may be contained in the image and that can be discarded from the image using Crop tool.
Image Cropping can be performed using two methods :
- Using crop() method
- Using Slicing Operator
Using crop() method –
crop() is an in-built method present in Wand library specially to perform crop operation on Image. Lets get forward towards Parameters in crop() function.
Syntax :
Python3
wand.image.crop(left, top, right, bottom, width,
height, reset_coords, gravity)
|
Parameters :
Parameter |
Input Type |
Description |
left |
numbers.Integral |
x-offset of the cropped image. default is 0 |
top |
numbers.Integral |
y-offset of the cropped image. default is 0 |
right |
numbers.Integral |
second x-offset of the cropped image. default is 0 |
bottom |
numbers.Integral |
second y-offset of the cropped image. default is 0 |
width |
numbers.Integral |
the width of the cropped image. default is the width of the image. this parameter and right parameter are exclusive each other. |
height |
numbers.Integral |
the height of the cropped image. default is the height of the image. this parameter and bottom parameter are exclusive each other. |
reset_ coords |
bool |
optional flag. If set, after the rotation, the coordinate frame will be relocated to the upper-left corner of the new image. By default is True. |
gravity |
GRAVITY_TYPES |
Optional flag. If set, will calculate the top and left attributes. This requires both width and height parameters to be included. |
Input Image –
Python3
from wand.image import Image
from wand.display import display
with Image(filename = 'gog.png' ) as img:
img.crop( 50 , 50 , 190 , 170 )
img.save(filename = 'croped_gog.png' )
display(img)
|
Output:
Using slicing operator –
Another way to perform crop operation is using slice operator.You can crop an image by [left:right, top:bottom] with maintaining the original. Slice operator is used with the original read file.
Syntax :
Python3
with Image(filename = 'filename.format' ) as img:
with img[left:right, top:bottom] as cropimg:
|
Input Image :
Python3
from wand.image import Image
from wand.display import display
with Image(filename = 'koala.jpeg' ) as img:
with img[ 100 : 250 , 120 : 250 ] as crpimg
crpimg.save(filename = 'crpimg.jpg' )
display(crpimg)
|
Output :
Last Updated :
18 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...