使用python写个程序,将不同尺寸的图片和车道线标注结果,统一改为1920*1080
- User
使用python写个程序,将不同尺寸的图片和车道线标注结果,统一改为1920*1080
- Assistant
要将不同尺寸的图片和车道线标注结果统一改为尺寸1920x1080,你可以用Python的Pillow库(PIL)来完成图像的调整。以下是一个简单的示范脚本,假设车道线标注是以矩形的形式给出的(例如,通过四个坐标点来定义每条车道线):
-
安装Pillow库(如果你尚未安装):
pip install Pillow -
编写脚本调整图片尺寸并绘制车道线标注:
from PIL import Image, ImageDraw def resize_image(input_image_path, output_image_path, size=(1920, 1080)): with Image.open(input_image_path) as image: # 调整图片大小来匹配目标尺寸 image_resized = image.resize(size, Image.ANTIALIAS) image_resized.save(output_image_path) def draw_lane_annotation(output_image_path, lane_lines): with Image.open(output_image_path) as img: draw = ImageDraw.Draw(img) # lane_lines 期望是一个包含每条车道线坐标的列表,如:[((x1,y1),(x2,y2)), ...] for line in lane_lines: # 可以调整线宽'width'和填充颜色'fill' draw.line(line, fill=(255,0,0), width=10) img.save(output_image_path) if __name__ == '__main__': input_image_path = 'path/to/your/input/image.jpg' output_image_path = 'path/to/your/output/image.jpg' # 示例车道线标注,每个元组表示一条线的起点和终点坐标 lane_lines = [((100, 100), (1000, 800)), ((150, 100), (1050, 800))] resize_image(input_image_path, output_image_path) draw_lane_annotation(output_image_path, lane_lines)
-
- User
不同尺寸的图片统一改为1920*1080,缺少的地方补黑边
- Assistant
要将不同尺寸的图片统一改为1920x1080的尺寸,并对不足的部分补黑边(而不是简单地重新缩放图像),我们可以使用Pillow库创建一个新的黑色背景图像,然后将原图像粘贴到中心位置。这种方法可以保持原图像的宽高比,同时达到目标尺寸。同时,在调整之后,我们也可以在图像上绘制车道线标注。以下是如何实现的示例代码:
首先,确保已经安装了Pillow库:
pip install Pillow然后,可以使用以下Python脚本来实现调整图片尺寸和补黑边的功能,同时在图片上绘制车道线标注:
from PIL import Image, ImageDraw def resize_and_pad(img_path, output_path, size=(1920, 1080), fill_color=(0, 0, 0)): img = Image.open(img_path) # 保持原图的宽高比 img.thumbnail(size, Image.ANTIALIAS) # 创建一个新的黑色背景图像 background = Image.new('RGB', size, fill_color) # 计算粘贴的位置,以使原图位于中心 bg_w, bg_h = size img_w, img_h = img.size offset = ((bg_w - img_w) // 2, (bg_h - img_h) // 2) background.paste(img, offset) # 保存或返回结果图像 background.save(output_path) def draw_lane_annotation(image_path, lane_lines): with Image.open(image_path) as img: draw = ImageDraw.Draw(img) # lane_lines 是一个包含每条车道线坐标的列表,如:[((x1,y1),(x2,y2)), ...] for line in lane_lines: # 可以调整线宽'width'和填充颜色'fill' draw.line(line, fill=(255, 0, 0), width=10) # 保存或返回结果图像 img.save(image_path) if __name__ == '__main__': input_image_path = 'path/to/your/input/image.jpg' output_image_path = 'path/to/your/output/image.jpg' # 示例车道线标注,每个元组表示一条线的起点和终点坐标 lane_lines = [((100, 100), (1000, 800)), ((150, 100), (1050, 800))] resize_and_pad(input_image_path, output_image_path) draw_lane_annotation(output_image_path, lane_lines)