1. 使用Pillow库处理图片Pillow是一个Python Imaging Library(PIL)的友好分支,它提供了一个简单而强大的接口来处理图像。以下是如何使用Pillow库来输出图片的步骤...
Pillow是一个Python Imaging Library(PIL)的友好分支,它提供了一个简单而强大的接口来处理图像。以下是如何使用Pillow库来输出图片的步骤:
pip install Pillowfrom PIL import Image
# 打开图片文件
img = Image.open('path_to_image.jpg')# 转换图片格式为PNG
img.save('path_to_output.png', 'PNG')# 调整图片大小为100x100像素
img = img.resize((100, 100))
img.save('path_to_output_resized.jpg')from PIL import ImageDraw, ImageFont
# 创建一个可以写文字的图片
draw = ImageDraw.Draw(img)
# 添加文字水印
draw.text((50, 50), 'Watermark', font=ImageFont.load_default(), fill=(255, 255, 255))
img.save('path_to_output_watermarked.jpg')OpenCV是一个专注于实时计算机视觉的开源库。它也可以用来处理和输出图片。
pip install opencv-pythonimport cv2
# 读取图片
image = cv2.imread('path_to_image.jpg')
# 显示图片
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()# 保存图片为PNG格式
cv2.imwrite('path_to_output.png', image)Matplotlib是一个用于绘图和可视化的库,它也可以用来显示和输出图片。
pip install matplotlibimport matplotlib.pyplot as plt
# 读取图片
img = plt.imread('path_to_image.jpg')
# 显示图片
plt.imshow(img)
plt.axis('off')
plt.show()ImageMagick是一个功能强大的图像处理库,它提供了命令行工具来处理图片。
(取决于操作系统,通常在包管理器中安装)
convert path_to_image.jpg path_to_output.pngPython内置库也能用来保存图片,虽然它的功能不如上面的库强大。
from io import BytesIO
from base64 import b64encode
# 假设img是一个PIL Image对象
bio = BytesIO()
img.save(bio, format='PNG')
image_str = b64encode(bio.getvalue()).decode()
# 这里image_str是一个可以保存为文件的图片的Base64编码字符串