Python中的魔杖crop()函数
裁剪图像是指选择图像区域并丢弃裁剪区域之外的所有内容。裁剪工具是一个重要的工具,因为它允许我们获取图像中唯一相关的部分。此外,有时图像中可能包含不需要的东西,可以使用裁剪工具从图像中丢弃。
可以使用两种方法执行图像裁剪:
- 使用crop() 方法
- 使用切片运算符
使用crop() 方法——
crop()是 Wand 库中的一个内置方法,专门用于对 Image 进行裁剪操作。让我们继续讨论crop()函数中的参数。
Syntax :
Python3
Python3
Python3
with Image(filename = 'filename.format') as img:
with img[left:right, top:bottom] as cropimg:
# other manipulation
Python3
# import Image from wand.image
from wand.image import Image
from wand.display import display
# read image using Image() function
with Image(filename = 'koala.jpeg') as img:
# cropping image using splitting operator
with img[100:250, 120:250] as crpimg
crpimg.save(filename ='crpimg.jpg')
# display image
display(crpimg)
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.
输入图像 -
Python3
wand.image.crop(left, top, right, bottom, width,
height, reset_coords, gravity)
# width and right parameter are exclusive each other
# height and bottom parameter are exclusive each other
输出:
使用切片运算符–
执行裁剪操作的另一种方法是使用切片运算符。您可以通过 [left:right, top:bottom] 裁剪图像,同时保持原始图像。切片运算符与原始读取文件一起使用。
Syntax :
Python3
with Image(filename = 'filename.format') as img:
with img[left:right, top:bottom] as cropimg:
# other manipulation
输入图像:
Python3
# import Image from wand.image
from wand.image import Image
from wand.display import display
# read image using Image() function
with Image(filename = 'gog.png') as img:
# crop image using crop() function
img.crop(50, 50, 190, 170)
# save resized image
img.save(filename = 'croped_gog.png')
display(img)
输出 :