Python图像处理之简单画板实现方法示例

时间:2022-09-29 20:24:39

本文实例讲述了Python图像处理之简单画板实现方法。分享给大家供大家参考,具体如下:

Python图像处理也是依赖opencv的Python接口实现的,Python语言简单易懂,简洁明了。本次实现画板涂鸦,一个是在里面画矩形,还有画线。其他也都可以扩展,本案例只做例程,思路是对鼠标事件的处理,以及滚动条调节颜色处理。鼠标事件就包含有左键按下,以及释放事件的处理。

?
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
import cv2
import numpy as np
# null function
def nothing(x):
  pass
Drawing = False
Mode = True
IX,IY = -1,-1
def drawCircle(Event,X,Y,Flags,Param):
  R = cv2.getTrackbarPos('R','Image')
  G = cv2.getTrackbarPos('G','Image')
  B = cv2.getTrackbarPos('B','Image')
#get color value
  Color = (B,G,R);
  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),3,Color,-1);
  elif Event == cv2.EVENT_LBUTTONUP:
    Drawing = False
#create image with 3 chanels
Img = np.zeros((660,660,3),np.uint8)
#create window
cv2.namedWindow('Image')
#create track bar, range for 0~255
cv2.createTrackbar('R','Image',0,255,nothing)
cv2.createTrackbar('G','Image',0,255,nothing)
cv2.createTrackbar('B','Image',0,255,nothing)
#set mouse ack
cv2.setMouseCallback('Image',drawCircle)
while(1):
  cv2.imshow('Image',Img)
  k = cv2.waitKey(10)&0xFF
  #switch draw mode
  if k == ord('m'):
    Mode = not Mode
  elif k == 27:
    break
#you must destroy all of sources
cv2.destroyAllWindows()

最后的效果图如下:

Python图像处理之简单画板实现方法示例

希望本文所述对大家Python程序设计有所帮助。

原文链接:https://blog.csdn.net/Touch_Dream/article/details/52199442