功能:在鼠标点击的位置画一个圆
import cv2
import numpy as np
def draw_circle(event,x,y,flag,param):
if event == cv2.EVENT_LBUTTONDBLCLK: #处理鼠标左键双击
cv2.circle(img,(x,y),100,(255,0,0),-1)#画一个圆
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle) #设置回调函数
while(1):
cv2.imshow('image',img)
if cv2.waitKey(20)&0xFF==27:
break #退出设置
cv2.destroyAllWindow()
程序功能:有两种模式 第一种是不按m时,鼠标左键按下绘制矩形鼠标抬起绘制结束 第二种是由圆圈构成的线
这里说明两个绘制函数的参数
cv2.rectangle(img, (ix,iy),(x,y),(0,2555,0),-1)#绘制矩形
函数中img是绘制到此图片中 (ix,iy)是矩形起点 (x,y)是矩形终点,(0,255,0)是矩形颜色,-1是线型,在此处是填充满;
cv2.circle(img,(x,y),3,(0,255,0),-1) #绘制圆
函数中(x,y)是绘制圆的中心,3是绘制半径 其他与上相同
import cv2
import numpy as np
drawing = False
mode = True
ix,iy = -1,-1
def draw_circle(event,x,y,flags,param):
global ix, iy ,drawing,mode
if event == cv2.EVENT_LBUTTONDOWN: #当鼠标按下时
drawing = True
ix,iy = x,y
elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON: #event表示鼠标移动 flags表示鼠标按下
if drawing == True:
if mode == True:
cv2.rectangle(img, (ix,iy),(x,y),(0,2555,0),-1)#绘制矩形
else:
cv2.circle(img,(x,y),3,(0,255,0),-1) #绘制圆
elif event == cv2.EVENT_LBUTTONUP: #鼠标键抬起
drawing = False
img = np.zeros((512,512,3),np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)
while(1):
cv2.imshow('image',img)
k = cv2.waitKey(1)&0xFF
if k == ord('m'):
mode = not mode
elif k == 27:
break