6.OpenCV 中的绘图函数
6.1画线
6.2画矩形
6.3画圆
6.4画椭圆
6.5画多边形
6.6在图片上添加文字
import numpy as np
import cv2
# Create a black image 5
img=np.zeros((512,512,3), np.uint8)#产生黑色图片
# Draw a diagonal blue line with thickness of 5 px
cv2.line(img,(0,0),(511,511),(255,0,0),5)#画线
cv2.rectangle(img,(384,0),(510,128),(0,255,0),3)#画矩形
cv2.circle(img,(447,63), 63, (0,0,255), -1)
#cv2.imshow(img)
cv2.ellipse(img,(256,256),(100,50),0,0,180,255,-1)#画椭圆
pts=np.array([[10,5],[20,30],[70,20],[50,10]], np.int32)#画多边形
pts=pts.reshape((-1,1,2))
# 这里 reshape 的第一个参数为 -1, 表明这一维的长度是根据后面的维度的计算出来的。
#cv2.imshow('a',img)
#cv2.waitKey(0)
font=cv2.FONT_HERSHEY_SIMPLEX
cv2.putText(img,'OpenCV',(10,500), font, 4,(255,255,255),2)#在图片上添加文字
winname = 'example'
cv2.namedWindow(winname)
cv2.imshow(winname, img)
cv2.waitKey(0)
cv2.destroyWindow(winname)
8.用滑动条做调色板
import cv2
import numpy as np
def nothing(x):
pass
#创建一副黑色图像
img=np.zeros((300,512,3),np.uint8)
cv2.namedWindow('image')
cv2.createTrackbar('R','image',0,255,nothing) ##创建滑块
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)
switch='0:OFF,1:ON'
cv2.createTrackbar(switch,'image',0,1,nothing)
while(1):
cv2.imshow('image',img)
k=cv2.waitKey(1)&0xFF
if k==27:
break
r=cv2.getTrackbarPos('R','image') ##获取滑块位置
g=cv2.getTrackbarPos('G','image')
b=cv2.getTrackbarPos('B','image')
s=cv2.getTrackbarPos(switch,'image')##控制开关
if s==0:
img[:]=0
else:
img[:]=[b,g,r]
cv2.destroyAllWindows()