1.绘制几种基本图形
import cv2
def draw_camera():
# you can see connected USB cameras by running : ls /dev/video* on the terminal
# for usb camera /dev/video2, the device_id will be 2
dispH=480
dispW=640
# Create the Camera instance
cam = cv2.VideoCapture('/dev/video0') #直接用0可能错误
cam.set(cv2.CAP_PROP_FRAME_WIDTH,dispW)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT,dispH)
print('USB Camera is now ready')
while True:
try:
# read the camera image
ret,frame = cam.read()
#drawing
# 矩形 (图片,(左上角),(右下角),颜色,线粗细)
frame=cv2.rectangle(frame,(340,100),(400,170),(0,255,0),7)
# 圆形 (图片, 圆心坐标,半径,颜色,线粗细(-1为实心))
frame=cv2.circle(frame,(320,240),50,(255,0,255),-1)
# 添加内容
fnt=cv2.FONT_HERSHEY_DUPLEX
# (图片,添加内容,位置,字体类型,字体大小,颜色,粗细)
frame=cv2.putText(frame,'my first text',(300,300),fnt,1.5,(255,0,150),2)
# 直线 (图片,起始位置,结束位置,颜色,线粗细)
frame=cv2.line(frame,(10,10),(630,470),(0,0,0),4)
# 箭头 (图片,起始,结束,颜色,线宽,线类型,箭头位置平移系数,箭头大小缩放系数)
frame=cv2.arrowedLine(frame,(10,470),(630,10),(255,255,255),2,0,0,0.2)
# display the frame
cv2.imshow('Video Frame', frame)
#set position
cv2.moveWindow('Video Frame',0,0)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
break
cam.release()
cv2.destroyAllWindows()
if __name__=="__main__":
draw_camera()
2.绘制移动矩形块
import cv2
def draw_camera():
# you can see connected USB cameras by running : ls /dev/video* on the terminal
# for usb camera /dev/video2, the device_id will be 2
dispH=480
dispW=640
# Create the Camera instance
cam = cv2.VideoCapture('/dev/video0') #直接用0可能错误
cam.set(cv2.CAP_PROP_FRAME_WIDTH,dispW)
cam.set(cv2.CAP_PROP_FRAME_HEIGHT,dispH)
# 高宽,起始位置,每次移动数
BW=int(.25*dispW)
BH=int(.15*dispH)
posX=10
posY=27
dx=2
dy=2
print('USB Camera is now ready')
while True:
try:
# read the camera image
ret,frame = cam.read()
# display the frame
cv2.moveWindow("Video Frame",0,0)
# 带有变量的矩形
frame=cv2.rectangle(frame,(posX,posY),(posX+BW,posY+BH),(255,0,0),-1)
cv2.imshow("Video Frame", frame)
# 更新位置
posX=posX+dx
posY=posY+dy
# 当矩形触及边界就会改变方向
if posX<=0 or posX+BW>dispW:
dx=dx*(-1)
if posY<=0 or posY+BH>dispH:
dy=dy*(-1)
if cv2.waitKey(25) & 0xFF == ord('q'):
break
except KeyboardInterrupt:
break
cam.release()
cv2.destroyAllWindows()
if __name__=="__main__":
draw_camera()