前两天想要把连续的不同帧的静态图片拼成一个GIF图片,但是原来的图片须要裁剪,而且存在许多张,幸好这么多张的图片裁剪的位置是一样的,于是我便实行用Python优雅地批量裁剪这些图片。
首先先容一下Python裁剪照片的原理。代码的输入是图片的地点和两个点的坐标,这两个点的坐标分别表示一个矩形的左上角极点和右下角极点,这个矩形就是你的裁剪地区。
写代码前,先引入一下所须要的库。- from PIL import Image, ImageDraw, ImageFont
复制代码 那么你一定会有个疑问,怎么确定图片矩形地区的极点位置呢?下面贴出一个在原图像上绘制边界框的代码。- def draw_bbox(image_path, bbox, output_path):
- """
- Draw bounding box on the image.
- Parameters:
- image_path (str): Path to the input image file.
- bbox (tuple): Bounding box coordinates (left, upper, right, lower).
- output_path (str): Path to save the image with bounding box.
- Returns:
- None
- """
- # Open image
- img = Image.open(image_path)
- # Draw bounding box
- draw = ImageDraw.Draw(img)
- draw.rectangle(bbox, outline="red", width=3)
- # Add text with coordinates
- font = ImageFont.truetype("arial.ttf", 20)
- draw.text((bbox[0], bbox[1]), f"{bbox}", fill="red", font=font)
- # Save image with bounding box
- img.save(output_path)
- input_image_path = r"F:\Desktop\woman.jpg"
- output_image_path = r"F:\Desktop\woman.jpg"
- crop_box = (700, 550, 1850, 1000) # Define crop box (left, upper, right, lower)
- draw_bbox(input_image_path, crop_box, output_image_path)
复制代码 crop_box(x1, y1, x2, y2),其中左上角极点表示为(x1, y1),右下角极点表示为(x2, y2)。但是你只能通过不断探索crop_box的取值,根据原图像上绘制的边界框,渐渐确定你最后的裁剪地区。下面给出运行draw_bbox代码的可视化例子。
用draw_bbox拿到符合的crop_box以后,下面给出裁剪图片的代码。- def crop_image(input_image_path, output_image_path, crop_box):
- """
- Crop an image using the specified crop box.
- Parameters:
- input_image_path (str): Path to the input image file.
- output_image_path (str): Path to save the cropped image.
- crop_box (tuple): Crop box coordinates (left, upper, right, lower).
- Returns:
- None
- """
- # Open image
- img = Image.open(input_image_path)
- # Crop image
- cropped_img = img.crop(crop_box)
- # Save cropped image
- cropped_img.save(output_image_path)
- print("Image cropped and saved successfully.")
复制代码 最后给出裁剪以后的可视化例子。
假如想要批量裁剪图片的话,就在外面套一个循环就可以了。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |