opencv 學習第4課 將鼠標作爲筆刷使用

 注意,要使用筆刷的話,需首先按下 m 鍵將默認模式轉變

import numpy as np 
import cv2 as cv 

drawing = False # true if mouse is pressed
mode = True # if True,draw rectangle. Press 'm' to toggle to curve
ix,iy = -1,-1

#mouse callback function
def draw_circle(event,x,y,flags,param):
	global ix,iy,drawing,mode

	#按下鼠標左鍵時 開始畫
	if event == cv.EVENT_LBUTTONDOWN:
		drawing = True
		ix,iy = x,y

	#鼠標移動時一直畫
	elif event == cv.EVENT_MOUSEMOVE:
		if drawing == True:
			if mode == True:
				cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
			else:
				cv.circle(img,(x,y),3,(0,0,255),-1)

	#鼠標左鍵鬆開時停止畫
	elif event == cv.EVENT_LBUTTONUP:
		drawing = False
		if mode == True:
			cv.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
		else:
			cv.circle(img,(x,y),5,(0,0,255),-1)


img = np.zeros((512,512,3),np.uint8)
cv.namedWindow('image')
cv.setMouseCallback('image',draw_circle)

while(1):
	cv.imshow('image',img)
	k = cv.waitKey(1) & 0xFF
	if k == ord('m'): #按下m鍵時 在畫矩形和畫線條之間切換
		mode = not mode
	elif k == 27:
		break

# 銷燬所有的窗口
cv.destroyAllWindows()

 

參考文獻:https://docs.opencv.org/4.1.0/db/d5b/tutorial_py_mouse_handling.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章