Python下使用Trackbar實現繪圖板
本次實驗利用到了cv2中的createTrackbar和getTrackbarPos函數實現一個繪圖板的功能,用戶可以選擇矩形或是畫筆模式,并設置調色板中的值來選擇顏色,再選擇畫筆大小,進行繪圖。除此之外,還可以用橡皮擦進行擦除,模式同樣也分為矩形和畫筆。
下面是具體的代碼:
import cv2import numpy as npdrawing = Falsemode = Trueix, iy = -1, -1def nothing(x): passdef draw_circle(event,x,y,flags,param): r = cv2.getTrackbarPos(’R’,’image’) g = cv2.getTrackbarPos(’G’,’image’) b = cv2.getTrackbarPos(’B’,’image’) color = (b,g,r) s = cv2.getTrackbarPos(’eraser’,’image’) if s == 1: color = (255,255,255) thin = cv2.getTrackbarPos(’thin’,’image’) 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: if drawing == True: if mode == True: cv2.rectangle(img, (ix,iy),(x,y),color,-1) else: cv2.circle(img,(x,y),thin,color,-1) elif event == cv2.EVENT_LBUTTONUP: drawing == Falseimg = np.zeros((512,512,3), np.uint8)img[:] = 255cv2.namedWindow(’image’)cv2.createTrackbar(’R’,’image’,0,255,nothing)cv2.createTrackbar(’G’,’image’,0,255,nothing)cv2.createTrackbar(’B’,’image’,0,255,nothing)cv2.createTrackbar(’eraser’,’image’,0,1,nothing)cv2.createTrackbar(’thin’,’image’,1,50,nothing)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
下面是運行的結果:
1.運行初始界面
2.選擇顏色分別進行矩形繪圖和畫筆繪圖,此圖中的畫筆的大小為1
3.此時的畫筆大小為15
4.使用大小為15的橡皮擦擦除面板(選擇了畫筆模式的橡皮擦)
5.使用大小為4的橡皮擦擦除面板(選擇了畫筆模式的橡皮擦)
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
