内容来自OpenCV-Python Tutorials 自己翻译整理
目标:
使用opencv画几何图形
学习如下函数 cv2.line(), cv2.circle() , cv2.rectangle(), cv2.ellipse(), cv2.putText()
画线:
import numpy as np
import cv2
#画图窗口大小设置为512*512 通常参数,可选1,3,4
img = np.zeros((512,512,4),np.uint8)
#画直线,参数为绘图窗口,起点,终点,颜色,粗细,连通性(可选4联通或8联通)
img = cv2.line(img,(100,0),(511,511),(255,0,0),5,8)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
矩形:
import numpy as np
import cv2
img = np.zeros((512,512,4),np.uint8)
#画矩形,参数为窗口,左上角坐标,右下角坐标,颜色,粗度
img = cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
画圆:
import numpy as np
import cv2
img = np.zeros((512,512,4),np.uint8)
#画圆函数,参数为窗口,圆心,半径,颜色,粗度(如果粗度为-1标示实心),连通性
img = cv2.circle(img,(447,63),50,(0,0,255),1,8)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
椭圆:
import numpy as np
import cv2
img = np.zeros((512,512,4),np.uint8)
#画椭圆函数,参数为窗口,椭圆中心,椭圆长轴短轴,椭圆逆时针旋转角度,椭圆起绘制起始角度,椭圆绘制结束角度,颜色,粗度,连通性
img = cv2.ellipse(img,(256,256),(100,50),100,36,360,(0,255,255),1,8)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
画多边形:
import numpy as np
import cv2
img = np.zeros((512,512,4),np.uint8)
pts = np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)
#转换成三维数组,表示每一维里有一个点坐标
pts = pts.reshape((-1,1,2))
#画多边形函数,参数为窗口,坐标,是否封闭,颜色
img = cv2.polylines(img,[pts],True,(0,255,255))
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
写字:
参数如下
1. 窗口
2. 要写到窗口上的字符
3. 字体位置,左下角
4. 字体类型,查询cv2.putText()函数的文档来查看字体
5. 字体大小
6. 常规参数,类似颜色,粗细,线条类型等等
import numpy as np
import cv2
img = np.zeros((512,512,4),np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2,cv2.LINE_AA)
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
|
|