OpenCV-Python -- Drawing Functions in OpenCV

学习目标

  • 用OpenCV画不同的几何形状
  • 函数: cv2.line(), cv2.circle() , cv2.rectangle(), cv2.ellipse(), cv2.putText()

函数通用参数

上面的所有函数的基本参数如下:

img:待画形状的目标对象;
color:形状的颜色。对于BGR,传递元组(255,0,0)蓝色。对于灰度图,传递标量值;
thickness:形状的粗细,如果给封闭的形状(比如圆)传递 -1,则会填充形状,默认值为 1
lineType:线的类型,8-connected, anti-aliased line etc。默认是8邻域方式,cv2.LINE-AA(anti-aliased,适合曲线);

画线(Drawing Line)

画线需要线的起点和终点。下面将创建黑色图像,画蓝色对角线。代码如下:

import numpy as np
import cv2

# Create a black image
img = np.zeros((512,512,3), np.uint8)

# Draw a diagonal blue line with thickness of 5 px
img = cv2.line(img,(0,0),(511,511),(255,0,0),5)
cv2.imshow("line: ", img)
cv2.waitKey(0)

结果如下:
在这里插入图片描述

画矩形(Drawing Rectangle)

画矩形需要传入左上角和右下角的坐标。那么在图像的右上角画出绿色矩形的代码如下:

img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)

画圆(Drawing Circle)

画圆需要圆心和半径,那么在上面的矩形中画圆,代码如下:

img = cv2.circle(img,(447,63), 63, (0,0,255), -1)

在这里插入图片描述

画椭圆(Drawing Ellipse)

函数 cv2.ellipse(),参数如下:
img:输入图像;
center:(x,y);
axes:长轴和短轴的一半长度,(256,256);
angle:椭圆整体旋转角度,顺时针方向,0;
startAngle and endAngle:表示从长轴顺时针方向的开始和结束,例如给定值0和360,则是完整的椭圆。下面的代码将画1/4个椭圆,90,180:

img = cv2.ellipse(img,(256,256),(256,256),0,90,180,255,-1)

在这里插入图片描述

画多边形(Drawing Polygon)

函数 cv2.polylines(),参数如下:
img:输入图像;
pts:顶点坐标,并且形状必须为 ROWSx1x2,ROWS是点的个数,类型为int32
isClosed:表示多边形是否闭合,如果是true,则闭合;
代码如下:

pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
pts = pts.reshape((-1,1,2)) # shape:(4, 1, 2)
img = cv2.polylines(img,[pts],True,(0,255,255))

在这里插入图片描述
在这里插入图片描述
:cv2.polylines()可以用于同时画多个直线。可以创建直线列表,传入函数。那么每条线会被独立画出来。

图像增加文本

增加文本,需要指定如下内容:

  • 文本内容
  • 文本位置
  • 类型
  • 文本尺度
  • color,thinkness,lineType等
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)

完整的代码和结果

import numpy as np
import cv2

# Create a black image
img = np.zeros((512, 512, 3), np.uint8)

# Draw a diagonal blue line with thickness of 5 px
img = cv2.line(img, (0, 0), (511, 511), (255, 0, 0), 5)

img = cv2.rectangle(img, (384, 0), (510, 128), (0, 255, 0), 3)
img = cv2.circle(img, (447, 63), 63, (0, 0, 255), -1)

# 椭圆
img = cv2.ellipse(img, (256, 256), (256, 256), 0, 90, 180, 255, -1)

# 多边形
pts = np.array([[10, 5], [20, 30], [70, 20], [50, 10]], np.int32)
pts = pts.reshape((-1, 1, 2))
print(pts)
print(pts.shape)
img = cv2.polylines(img, [pts], False, (0, 255, 255))

font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img, 'OpenCV', (10, 500), font, 4, (255, 255, 255), 2, cv2.LINE_AA)

cv2.imshow('line: ', img)
cv2.waitKey(0)

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值