Python基于opencv实现的简单画板功能示例

(编辑:jimmy 日期: 2024/11/16 浏览:2)

本文实例讲述了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基于opencv实现的简单画板功能示例

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》、《Python文件与目录操作技巧汇总》及《Python图片操作技巧总结》

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

一句话新闻
微软与英特尔等合作伙伴联合定义“AI PC”:键盘需配有Copilot物理按键
几个月来,英特尔、微软、AMD和其它厂商都在共同推动“AI PC”的想法,朝着更多的AI功能迈进。在近日,英特尔在台北举行的开发者活动中,也宣布了关于AI PC加速计划、新的PC开发者计划和独立硬件供应商计划。
在此次发布会上,英特尔还发布了全新的全新的酷睿Ultra Meteor Lake NUC开发套件,以及联合微软等合作伙伴联合定义“AI PC”的定义标准。