本文实例讲述了python基于opencv实现的简单画板功能。分享给大家供大家参考,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
import cv2 import numpy as np drawing = false # true if mouse is pressed ix,iy = - 1 , - 1 def nothing(x): pass # mouse callback function def draw_circle(event,x,y,flags,param): global ix,iy,drawing g = param[ 0 ] b = param[ 1 ] r = param[ 2 ] shape = param[ 3 ] if event = = cv2.event_lbuttondown: drawing = true ix,iy = x,y elif event = = cv2.event_mousemove: if drawing = = true: if shape = = 0 : cv2.rectangle(img,(ix,iy),(x,y),(g,b,r), - 1 ) else : cv2.circle(img,(x,y), 5 ,(g,b,r), - 1 ) elif event = = cv2.event_lbuttonup: drawing = false if shape = = 0 : cv2.rectangle(img,(ix,iy),(x,y),(g,b,r), - 1 ) else : cv2.circle(img,(x,y), 5 ,(g,b,r), - 1 ) # create a black image, a window img = np.zeros(( 300 , 512 , 3 ), np.uint8) cv2.namedwindow( 'image' ) # create trackbars for color change cv2.createtrackbar( 'r' , 'image' , 0 , 255 ,nothing) cv2.createtrackbar( 'g' , 'image' , 0 , 255 ,nothing) cv2.createtrackbar( 'b' , 'image' , 0 , 255 ,nothing) # create switch for on/off functionality switch1 = '0 : off \n1 : on' switch2 = '0: rectangle \n1: line ' cv2.createtrackbar(switch1, 'image' , 0 , 1 ,nothing) cv2.createtrackbar(switch2, 'image' , 0 , 1 ,nothing) while ( 1 ): cv2.imshow( 'image' ,img) k = cv2.waitkey( 1 ) & 0xff # get current positions of four trackbars if k = = 27 : break r = cv2.gettrackbarpos( 'r' , 'image' ) g = cv2.gettrackbarpos( 'g' , 'image' ) b = cv2.gettrackbarpos( 'b' , 'image' ) shape = cv2.gettrackbarpos(switch2, 'image' ) s = cv2.gettrackbarpos(switch1, 'image' ) if s = = 0 : img[:] = 0 else : if k = = 27 : break cv2.setmousecallback( 'image' ,draw_circle,(b,g,r,shape)) cv2.destroyallwindows() |
运行效果:
希望本文所述对大家python程序设计有所帮助。
原文链接:https://blog.csdn.net/xuminnju/article/details/79588161