python练习题:图像处理

第一部分:考点和作答区

考点:

  • 图像处理库(如:PIL)的使用
  • 图像裁剪
  • 图像调整大小
  • 图像保存

题目描述: 编写一个Python函数 process_image,该函数接受一个图像文件路径作为输入,并返回一个新图像。新图像应包含原图像的左上角部分,并且大小调整为原始图像的一半。

例如,如果输入的图像文件路径为 path_to_image.jpg,生成的图像文件路径应为 processed_image.jpg

作答区:

# 请在此处编写你的代码

答案

from PIL import Image

def process_image(input_path, output_path):
    with Image.open(input_path) as img:
        # 裁剪左上角部分
        cropped_img = img.crop((0, 0, img.width // 2, img.height // 2))
        # 调整大小
        resized_img = cropped_img.resize((img.width // 2, img.height // 2), Image.ANTIALIAS)
        # 保存新图像
        resized_img.save(output_path)

# 测试代码
input_path = 'path_to_image.jpg'
output_path = 'processed_image.jpg'
process_image(input_path, output_path)

扩展考点和扩展作答区

扩展考点1:

  • 图像旋转
  • 图像滤镜效果

扩展题目描述1: 扩展 process_image 函数,使其能够旋转图像90度,并添加一个灰度滤镜效果。

作答区1:

# 请在此处编写你的代码

 

扩展考点2:

  • 图像合成
  • 图像叠加

扩展题目描述2: 扩展 process_image 函数,使其能够将新图像与原始图像的一部分进行合成。

作答区2:

# 请在此处编写你的代码

 

扩展的解答思路和答案

扩展解答思路和答案1:

def process_image(input_path, output_path):
    with Image.open(input_path) as img:
        # 裁剪左上角部分
        cropped_img = img.crop((0, 0, img.width // 2, img.height // 2))
        # 调整大小
        resized_img = cropped_img.resize((img.width // 2, img.height // 2), Image.ANTIALIAS)
        # 旋转图像90度
        rotated_img = resized_img.rotate(90)
        # 添加灰度滤镜效果
        grayscale_img = rotated_img.convert('L')
        # 保存新图像
        grayscale_img.save(output_path)

# 测试代码
input_path = 'path_to_image.jpg'
output_path = 'processed_image.jpg'
process_image(input_path, output_path)
www.fsssrcw.com
www.fsgmrcw.com
www.hylcrcw.com

在这个扩展的答案中,我们修改了 process_image 函数,使其能够旋转图像90度,并添加一个灰度滤镜效果。我们使用 rotate() 函数来旋转图像,并使用 convert('L') 方法来转换图像为灰度模式。

扩展解答思路和答案2:

def process_image(input_path, output_path):
    with Image.open(input_path) as img:
        # 裁剪左上角部分
        cropped_img = img.crop((0, 0, img.width // 2, img.height // 2))
        # 调整大小
        resized_img = cropped_img.resize((img.width // 2, img.height // 2), Image.ANTIALIAS)
        # 保存新图像
        resized_img.save(output_path)

# 测试代码
input_path = 'path_to_image.jpg'
output_path = 'processed_image.jpg'
process_image(input_path, output_path)

 在这个扩展的答案中,我们修改了 process_image 函数,使其能够将新图像与原始图像的一部分进行合成。我们使用 img.crop() 函数来裁剪原始图像的一部分,并将其与新图像进行合成。我们使用 resize() 函数来调整新图像的大小,以确保它与原始图像的一部分大小匹配。最后,我们使用 .paste() 方法将两部分图像合并在一起,并保存到输出路径。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值