Python基于opencv实现的简单画板功能示例
程序员文章站
2022-04-25 18:24:32
本文实例讲述了python基于opencv实现的简单画板功能。分享给大家供大家参考,具体如下:
import cv2
import numpy as np
d...
本文实例讲述了python基于opencv实现的简单画板功能。分享给大家供大家参考,具体如下:
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相关内容感兴趣的读者可查看本站专题:《python数学运算技巧总结》、《python数据结构与算法教程》、《python函数使用技巧总结》、《python字符串操作技巧汇总》、《python入门与进阶经典教程》、《python文件与目录操作技巧汇总》及《python图片操作技巧总结》
希望本文所述对大家python程序设计有所帮助。