python ImageDraw类实现几何图形的绘制与文字的绘制


Posted in Python onFebruary 26, 2020

python PIL图像处理模块中的ImageDraw类支持各种几何图形的绘制和文本的绘制,如直线、椭圆、弧、弦、多边形以及文字等。

下面直接通过示例来进行说明:

#-*- coding: UTF-8 -*- 
 
import numpy as np
from PIL import Image
from PIL import ImageDraw
from PIL import ImageFont
 
 
def draw_test():
 
 #生成深蓝色绘图画布
 array = np.ndarray((480, 640, 3), np.uint8)
 
 array[:, :, 0] = 0
 array[:, :, 1] = 0
 array[:, :, 2] = 100
 
 image = Image.fromarray(array)
 
 #创建绘制对象
 draw = ImageDraw.Draw(image)
 
 #绘制直线
 draw.line((20, 20, 150, 150), 'cyan')
 
 #绘制矩形
 draw.rectangle((100, 200, 300, 400), 'black', 'red')
 
 #绘制弧
 draw.arc((100, 200, 300, 400), 0, 180, 'yellow')
 draw.arc((100, 200, 300, 400), -90, 0, 'green')
 
 #绘制弦
 draw.chord((350, 50, 500, 200), 0, 120, 'khaki', 'orange')
 
 #绘制圆饼图
 draw.pieslice((350, 50, 500, 200), -150, -30, 'pink', 'crimson')
 
 #绘制椭圆
 draw.ellipse((350, 300, 500, 400), 'yellowgreen', 'wheat')
 #外切矩形为正方形时椭圆即为圆
 draw.ellipse((550, 50, 600, 100), 'seagreen', 'skyblue') 
 
 #绘制多边形
 draw.polygon((150, 180, 200, 180, 250, 120, 230, 90, 130, 100), 'olive', 'hotpink')
 
 #绘制文本
 font = ImageFont.truetype("consola.ttf", 40, encoding="unic")#设置字体
 draw.text((100, 50), u'Hello World', 'fuchsia', font)
 
 image.show()
 
 return

首先,通过ImageDraw类创建一个绘制对象draw;

draw.line():直线的绘制,第一个参数指定的是直线的端点坐标,形式为(x0, y0, x1, y1),第二个参数指定直线的颜色;

draw.rectangle():矩形绘制,第一个参数指定矩形的对角线顶点(左上和右下),形式为(x0, y0, x1, y1),第二个指定填充颜色,第三个参数指定边界颜色;

draw.arc():(椭)圆弧的绘制,第一个参数指定弧所在椭圆的外切矩形,第二、三两个参数分别是弧的起始和终止角度, 第四个参数是填充颜色,第五个参数是线条颜色;

draw.chord():弦的绘制,和弧类似,只是将弧的起始和终止点通过直线连接起来;

draw.pieslice():圆饼图的绘制,和弧与弦类似,只是分别将起始和终止点与所在(椭)圆中心相连;

draw.ellipse():椭圆的绘制,第一个参数指定椭圆的外切矩形, 第二、三两个参数分别指定填充颜色和线条颜色,当外切矩形是正方形时,椭圆即为圆;

draw.polygon():绘制多边形,第一个参数为多边形的端点,形式为(x0, y0, x1, y1, x2, y2,……),第二、三两个参数分别指定填充颜色和线条颜色;

draw.text():文字的绘制,第一个参数指定绘制的起始点(文本的左上角所在位置),第二个参数指定文本内容,第三个参数指定文本的颜色,第四个参数指定字体(通过ImageFont类来定义)。

绘制结果如下:

python ImageDraw类实现几何图形的绘制与文字的绘制

最后,补充一下python中所支持的颜色,如下图所示:

python ImageDraw类实现几何图形的绘制与文字的绘制

另外,颜色也可以使用"#"加上6位16进制字符串表示如“#ff0000”,则和“red”等价,前两位表示R通道的值,中间两位表示G通道的值,最后两位表示B通道的值。

PS:opencv+python 实现基本图形的绘制及文本的添加

import cv2
import numpy as np
import os
 
class Drawing(object):
 """
 使用opencv绘制图形,支持直线,矩形,圆形,椭圆,多边形以及被标注文字添加
 """
 chart_list = ['line', 'rectangle', 'circle', 'ellipse', 'polylines', 'puttext']
 
 def __init__(self, src_img, dst_img, chart, dict_args):
  self.src_img = os.path.normpath(src_img)
  self.dst_img = os.path.normpath(dst_img)
  self.chart = chart
  self.dict_args = dict_args
  # 颜色不传默认为红色
  self.color = dict_args['color'] if dict_args.has_key('color') else (0,0,255)
  # 线条粗细不传默认为 2
  self.thickness = dict_args['thickness'] if dict_args.has_key('thickness') else 2
 
 def handle(self):
  # 导入图片
  self.src_img = cv2.imread(self.src_img)
  if self.chart not in self.chart_list:
   print 'must input your right parameter'
   return
  if self.chart == 'line':
   # 画直线
   self.start = self.dict_args['start']
   self.end = self.dict_args['end']
   self.draw_line()
  elif self.chart == 'rectangle':
   # 画矩形
   self.top_left = self.dict_args['top_left']
   self.bottom_right = self.dict_args['bottom_right']
   self.draw_rectangle()
  elif self.chart == 'circle':
   # 画圆形
   self.center = self.dict_args['center']
   self.radius = self.dict_args['radius']
   self.draw_circle()
  elif self.chart == 'ellipse':
   # 画椭圆
   self.center = self.dict_args['center']
   self.axes = self.dict_args['axes']
   # 旋转角度,起始角度,终止角度 可不传参,使用默认值
   self.angle = self.dict_args['angle'] if self.dict_args.has_key('angle') else 0
   self.startangle = self.dict_args['startangle'] if self.dict_args.has_key('startangle') else 0
   self.endangle = self.dict_args['endangle'] if self.dict_args.has_key('endangle') else 360
   self.draw_ellipse()
  elif self.chart == 'polylines':
   # 画多边形
   if not isinstance(self.dict_args['points'], list):
    self.pts = list(self.dict_args['points'])
   self.pts = np.array(self.dict_args['points'], np.int32)
   self.close = self.dict_args['close'] if self.dict_args.has_key('close') else True
   self.draw_polylines()
  else:
   # 标注文本
   self.text = self.dict_args['text']
   self.position = self.dict_args['position']
   # 字体,文字大小 可不传参,使用默认值
   self.font = self.dict_args['font'] if self.dict_args.has_key('font') else cv2.FONT_HERSHEY_SIMPLEX
   self.size = self.dict_args['size'] if self.dict_args.has_key('size') else 1
   self.add_text()
  cv2.imwrite(self.dst_img, self.src_img)
 
 def draw_line(self):
  # 划线
  # 输入参数分别为图像,开始坐标,结束坐标,颜色数组,粗细
  cv2.line(self.src_img, self.start, self.end, self.color, self.thickness)
 
 def draw_rectangle(self):
  # 画矩形
  # 输入参数分别为图像、左上角坐标、右下角坐标、颜色数组、粗细
  cv2.rectangle(self.src_img, self.top_left, self.bottom_right, self.color, self.thickness)
 
 def draw_circle(self):
  # 画圆形
  # 输入参数为图像,圆心,半径,线条颜色,粗细
  cv2.circle(self.src_img, self.center, self.radius, self.color, self.thickness)
 
 def draw_ellipse(self):
  # 画椭圆
  # 输入参数为图像,中心,(长轴,短轴),旋转角度,起始角度,终止角度,线条颜色,粗细
  cv2.ellipse(self.src_img, self.center, self.axes, self.angle, self.startangle,self.endangle, self.color, self.thickness)
 
 def draw_polylines(self):
  # 画多边形
  # 输入参数为图像,多边形各个顶点坐标,是否连成封闭图形,线的颜色,粗细
  cv2.polylines(self.src_img, [self.pts], self.close, self.color, self.thickness)
 
 def add_text(self):
  # 标注文本
  # 输入参数为图像、文本、位置、字体、大小、颜色数组、粗细
  cv2.putText(self.src_img, self.text, self.position, self.font, self.size, self.color, self.thickness)

以上就是python ImageDraw类实现几何图形的绘制与文字的绘制的详细内容,更多关于python 几何图形的绘制的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
使用PDB模式调试Python程序介绍
Apr 05 Python
浅述python中argsort()函数的实例用法
Mar 30 Python
python多线程socket编程之多客户端接入
Sep 12 Python
python实现SOM算法
Feb 23 Python
Python3爬虫学习之爬虫利器Beautiful Soup用法分析
Dec 12 Python
用python3 返回鼠标位置的实现方法(带界面)
Jul 05 Python
Django框架视图函数设计示例
Jul 29 Python
Pycharm中import torch报错的快速解决方法
Mar 05 Python
PyQt5中向单元格添加控件的方法示例
Mar 24 Python
在Python中实现字典反转案例
Dec 05 Python
python 指定源路径来解决import问题的操作
Mar 04 Python
python中 .npy文件的读写操作实例
Apr 14 Python
Python列表解析操作实例总结
Feb 26 #Python
Python图像处理库PIL的ImageFilter模块使用介绍
Feb 26 #Python
python实现低通滤波器代码
Feb 26 #Python
Python解释器及PyCharm工具安装过程
Feb 26 #Python
Python基础之列表常见操作经典实例详解
Feb 26 #Python
Python TKinter如何自动关闭主窗口
Feb 26 #Python
Flask和pyecharts实现动态数据可视化
Feb 26 #Python
You might like
vBulletin Forum 2.3.xx SQL Injection
2006/10/09 PHP
PHP里的中文变量说明
2011/07/23 PHP
PHP使用get_headers函数判断远程文件是否存在的方法
2014/11/28 PHP
ThinkPHP实现支付宝接口功能实例
2014/12/02 PHP
codeigniter实现get分页的方法
2015/07/10 PHP
PHP基本语法实例总结
2016/09/09 PHP
PHP判断json格式是否正确的实现代码
2017/09/20 PHP
PHP的curl函数的用法总结
2019/02/14 PHP
javascript实现类似于新浪微博搜索框弹出效果的方法
2015/07/27 Javascript
微信JS-SDK自定义分享功能实例详解【分享给朋友/分享到朋友圈】
2016/11/25 Javascript
JS实现动态修改table及合并单元格的方法示例
2017/02/20 Javascript
ionic中的$ionicPlatform.ready事件中的通用设置
2017/06/11 Javascript
详解vue-router 动态路由下子页面多页共活的解决方案
2019/12/22 Javascript
python刷投票的脚本实现代码
2014/11/08 Python
通过源码分析Python中的切片赋值
2017/05/08 Python
Python文本统计功能之西游记用字统计操作示例
2018/05/07 Python
pytorch索引查找 index_select的例子
2019/08/18 Python
python tkinter组件使用详解
2019/09/16 Python
pycharm sciview的图片另存为操作
2020/06/01 Python
python 瀑布线指标编写实例
2020/06/03 Python
HTML5 input placeholder 颜色修改示例
2014/05/30 HTML / CSS
使用html2canvas.js实现页面截图并显示或上传的示例代码
2018/12/18 HTML / CSS
英国Amara家居法国网站:家居装饰,现代装饰和豪华礼品
2016/12/15 全球购物
幼儿园六一儿童节主持节目串词
2014/03/21 职场文书
幼儿园保育员岗位职责
2014/04/13 职场文书
大学本科生职业生涯规划书范文
2014/09/14 职场文书
民警个人对照检查剖析材料
2014/09/17 职场文书
区长工作作风个人整改措施
2014/10/01 职场文书
教师自查自纠工作情况报告
2014/10/29 职场文书
管辖权异议上诉状
2015/05/23 职场文书
MySQL锁机制
2021/04/05 MySQL
PostgreSQL通过oracle_fdw访问Oracle数据的实现步骤
2021/05/21 PostgreSQL
解决tk mapper 通用mapper的bug问题
2021/06/16 Java/Android
一次项目中Thinkphp绕过禁用函数的实战记录
2021/11/17 PHP
Vertica集成Apache Hudi重磅使用指南
2022/03/31 Servers
python内置模块之上下文管理contextlib
2022/06/14 Python