在探索图像处理的世界之前,了解一些基础知识是非常重要的。色彩和像素是构成数字图像的基石。
名称 | RGB值 | 名称 | RGB值 |
---|---|---|---|
白色 | (255, 255, 255) | 红色 | (255, 0, 0) |
绿色 | (0, 255, 0) | 蓝色 | (0, 0, 255) |
灰色 | (128, 128, 128) | 黄色 | (255, 255, 0) |
黑色 | (0, 0, 0) | 紫色 | (128, 0, 128) |
Pillow是Python的一个图像处理库,它是Python Imaging Library (PIL) 的一个更新分支,它支持多种图像文件格式的操作,包括打开、显示、裁剪、缩放、旋转、像素操作、绘图等。
要安装Pillow,可以使用pip:
pip install pillow
Pillow的核心是Image
类,它允许你读取和操作图像。以下是一些基础的操作示例:
from PIL import Image
image = Image.open('guido.jpg')
print(image.format) # 输出图像格式,比如JPEG
print(image.size) # 输出图像尺寸,比如(500, 750)
print(image.mode) # 输出图像模式,比如RGB
image.show() # 显示图像
image.crop((80, 20, 310, 360)).show()
image.thumbnail((128, 128))
image.show()
guido_image = Image.open('guido.jpg')
guido_head = guido_image.crop((80, 20, 310, 360))
luohao_image = Image.open('luohao.png')
luohao_image.paste(guido_head.resize((int(guido_head.size[0] / 1.5), int(guido_head.size[1] / 1.5))), (172, 40))
luohao_image.show()
image.rotate(45).show()
image.transpose(Image.FLIP_TOP_BOTTOM).show()
for x in range(80, 310):
for y in range(20, 360):
image.putpixel((x, y), (128, 128, 128))
image.show()
from PIL import ImageFilter
image.filter(ImageFilter.CONTOUR).show()
ImageDraw
模块提供了绘图功能,可以绘制形状和添加文字。以下是一个绘图示例:
import random
from PIL import Image, ImageDraw, ImageFont
def random_color():
return random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
image = Image.new('RGB', (800, 600), color=(255, 255, 255))
drawer = ImageDraw.Draw(image)
font = ImageFont.truetype('Kongxin.ttf', 32)
drawer.text((300, 50), 'Hello, world!', fill=(255, 0, 0), font=font)
drawer.line((0, 0, 800, 600), fill=(0, 0, 255), width=2)
drawer.line((800, 0, 0, 600), fill=(0, 0, 255), width=2)
drawer.rectangle((300, 200, 500, 300), outline=(255, 0, 0), width=2)
for _ in range(4):
drawer.ellipse((150, 220, 310, 380), outline=random_color(), width=8)
image.show()
image.save('result.png')
Python提供了强大的库来处理图像,如Pillow和OpenCV,这些库可以帮助我们完成从简单的图像编辑到复杂的图像分析的各种任务。通过编程,我们可以自动化许多重复性的工作,提高效率。图像处理只是Python应用的冰山一角,它的能力远不止于此。继续探索Python的世界,你会发现更多令人兴奋的可能性。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。