您好,
会员登录 快速注册
退出 ( 条未读消息)
关于本站 意见反馈 首页

公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!
全部文章分类
  • 人工智能 >

  • 编程语言 >

  • WPF系列 >

  • ASP.NET系列 >

  • Linux >

  • 数据库 >

  • 嵌入式 >

  • WEB技术 >

  • PLC系列 >

  • 微服务与框架 >

  • 小宅DIY >

  • 学习资料 >

OpenCv基础 ANN车牌识别 yolov5车牌识别 指针式仪表识别 ROS系列 YOLO Halcon Detectron2 昇腾AI ChatGPT在线体验 英伟达JETSON ChatGLM ChatTTS FunASR 地平线 ByteTrack 魔搭社区 LangChain
C C# C++ Python Java Go
WPF
ASP.NET小功能 GPS定位系统-MVC GPS定位系统-VUE ASP.NET WebRTC
Linux Linux内核 Shell MakeFile
MySql SqlServer Oracle
STM8 STM32 51单片机
VUE入门 HTML JavaScript CSS layui镜像网站 ElementUi中文官网 element-plus 图标
三菱 欧姆龙 西门子 施耐德 松下 台达
IOTSharp IOTGateway ABP FRAMEWORK Docker
亚克力音响 编程仙途:智驭万法
面试题与技巧 Python入门技能树 微软C#教程
首页 编程之美 工具下载 全国就业 流量地图 文心一言
OpenCv基础
内容介绍与资料分享 C# OpenCv环境搭建 C++ OpenCv环境搭建 Python OpenCv环境搭建 Java OpenCv环境搭建 OpenCv组件结构解析 OpenCv命名规范 OpenCv基本专业术语与方法 OpenCV 常用函数与构造体详细说明 创建画布 打开一张图片 利用imwrite生成透明png图像 图像打开、混合显示和输出 图像腐蚀 blur图像模糊(均值滤波) sobel边缘检测 canny边缘检测 Scharr滤波器 程序性能检测及优化 视频播放 摄像头录像与播放 双摄像头操作与图像相似度检测 颜色空间转换与物体追踪 彩色目标追踪 光流法运动目标检测 OpenCV中的稠密光流 背景减除 点追踪 人脸识别 支持向量机之SVM引导 支持向量机之处理线性不可分数据 ROI矩形截取 鼠标绘制矩形 用OpenCV进行基本绘图 绘图函数(python中文显示) 把鼠标当画笔 用滑动条做调色板 图像的基础操作 图像上的算术运算 多通道图像混合 图像的亮度、对比度调整 XML和YAML文件的写入 XML和YAML文件的读取 卷积操作 三种线性滤波 两种非线性滤波 7种图像处理形态学(1) 7种图像处理形态学(2) 漫水填充 图像缩放与图像金字塔 二值化基本阈值操作 图像阈值 Laplacian图像变换(拉普拉斯算子) 霍夫变换HoughLines边缘检测与线性矢量 霍夫变换HoughLinesP边缘检测与线性矢量 霍夫变换HoughCircles边缘检测与线性矢量 LSD快速直线检测 几何变换 remap重映射 remap实现多种重映射 仿射变换综合示例 直方图均衡化 CLAHE有限对比适应性直方图均衡化 draw最大的轮廓 轮廓的性质 点到多边形的最短距离 形状匹配 椭圆拟合与直线拟合 基础轮廓查找 查找并绘制轮廓综合示例 凸缺陷/凸包检测 凸包检测 创建包围轮廓的矩形边界 创建包围轮廓的圆形边 创建包围轮廓的矩形和圆形边界框 查找和绘制图片轮廓矩 分水岭算法 图像修补 H-S二维直方图的绘制/2D直方图 一维直方图的绘制 RGB三色直方图的绘制 直方图对比 使用掩膜绘制直方图 直方图反向投影 模板匹配 多对象模板匹配 cornerHarris角点检测 cornerHarris角点检测综合示例 Shi-Tomasi角点检测 亚像素级角点检测 角点检测的FAST算法(FAST特征检测器) 颜色识别 warpPerspective透视变换 SURF/SIFT特征点检测 SURF/SIFT特征描述 使用FLANN进行特征点匹配 FLANN结合SURF/SIFT进行关键点的描述和匹配 寻找已知物体(一) 寻找已知物体(二) 目标查找与跟踪 - Meanshift与CamShift BRIEF描述符 ORB ORB算法描述与匹配 LUT 图像灰度调整 离散傅里叶变换 双目摄像头与图像拼接 环境亮度检测 stitching 全景拼接 Maze-Solver迷宫解密 使用Haar分类器之面部检测 使用Haar分类器之行人检测 OpenCv Haar/LBP/HOG分类器-人脸识别 斑点检测 使用GrabCut算法进行交互式前景提取 对极几何 摄像机标定 姿势估计 立体图像中的深度地图 OpenCv中的KNN KNN手写数字识别 ​SVM手写数字识别(使用SVM进行手写数据OCR) 英文字母的OCR 预测手写数字(预测不准) K值聚类(一) K值聚类(二) 计算摄影学-图像去噪 高动态范围成像(HDRI或HDR) MSER区域检测 二维码、条形码识别 删除图像中的水印 OpenCv深度学习dnn Kinect-深度相机 OpenCv常用数学算法 360度旋转直线绘制 向量延长线上的像素扫描 Tools工具包-窗体分配
把鼠标当画笔
图像的基础操作
激萌の小宅 小宅博客网 OpenCv基础

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

用滑动条做调色板

当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


当前章节共2个demo

demo1:绘制不同颜色的圆和矩形

1.gif


demo2:调节画布颜色

1 (1).gif


C#版本运行代码如下:

demo1:绘制不同颜色的圆和矩形演示代码如下:

using OpenCvSharp;
using System;

namespace ConsoleApp
{
  internal class Program
  {
    public static Mat img = new Mat();
    // 矩形和圆形模式切换
    public static bool mode = false;
    public static bool drawing = false;
    public static int ix = -1, iy = -1;
    public static void draw_circle(MouseEventTypes @event, int x, int y, MouseEventFlags flags, IntPtr userData)
    {
      int r = Cv2.GetTrackbarPos("R", "image");
      int g = Cv2.GetTrackbarPos("G", "image");
      int b = Cv2.GetTrackbarPos("B", "image");

      // 当按下左键是返回起始位置坐标
      if (@event == MouseEventTypes.LButtonDown)
      {
        drawing = true;
        ix = x;
        iy = y;
      }
      if (@event == MouseEventTypes.MouseMove)
      {
        if(drawing)
        {
          if (mode)
          {
            Cv2.Rectangle(img, new Point(ix, iy), new Point(x, y), new Scalar(b, g, r), -1);
          }
          else
          {
            // 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
            Cv2.Circle(img, new Point(x, y), 3, new Scalar(b, g, r), -1);

            //下面注释掉的代码是起始点为圆心,起点到终点为半径的
            //int r = (int)(Math.Sqrt((x - ix) * (x - ix) + (y - iy) * (y - iy)));
            //Cv2.Circle(img, new Point(x, y), r, new Scalar(b, g, r), -1);
          }
        } 
      }
      // 当鼠标松开停止绘画。
      if (@event == MouseEventTypes.LButtonUp)
      {
        drawing = false;
      }
    }

    public static void Main(string[] args)
    {
      img = new Mat(new Size(512, 512), MatType.CV_8UC3, new Scalar(0, 0, 0));
      Cv2.NamedWindow("image", WindowFlags.AutoSize);

      Cv2.CreateTrackbar("R", "image", 255, null);
      Cv2.CreateTrackbar("G", "image", 255, null);
      Cv2.CreateTrackbar("B", "image", 255, null);
      Cv2.SetMouseCallback("image", new MouseCallback(draw_circle));
      while (true)
      {
        Cv2.ImShow("image", img);
        if (Cv2.WaitKey(1) == 'm')
        {
          mode = !mode;
        }
      }
    }
  }
}


demo2:调节画布颜色,演示代码如下:

using OpenCvSharp;

namespace ConsoleApp
{
  internal class Program
  {
    public static void Main(string[] args)
    {
      string swit = "0 : OFF \n1 : ON";
      Mat img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(0, 0, 0));
      Cv2.NamedWindow("image", WindowFlags.AutoSize);

      Cv2.CreateTrackbar("R", "image", 255, null);
      Cv2.CreateTrackbar("G", "image", 255, null);
      Cv2.CreateTrackbar("B", "image", 255, null);
      Cv2.CreateTrackbar(swit, "image", 1, null);

      while (true)
      {
        int r = Cv2.GetTrackbarPos("R", "image");
        int g = Cv2.GetTrackbarPos("G", "image");
        int b = Cv2.GetTrackbarPos("B", "image");
        int s = Cv2.GetTrackbarPos(swit, "image");

        if (s == 0)
          img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(0, 0, 0));
        else
          img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(b, g, r));

        Cv2.ImShow("image", img);
        Cv2.WaitKey(1);
        img.Dispose();
      }
    }
  }
}


C++版本运行代码如下:

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

#define DEMOID 0

// 绘制不同颜色的圆和矩形演示代码如下
#if DEMOID == 0
// 当鼠标按下时变为 True
bool drawing = false;
// 矩形和圆形模式切换
bool mode = false;
// 如果 mode 为 true 绘制矩形。按下'm' 变成绘制曲线。 mode=True
int ix = -1, iy = -1;

void on_MouseHandle(int event, int x, int y, int flags, void* param)
{
    int r = getTrackbarPos("R", "image");
    int g = getTrackbarPos("G", "image");
    int b = getTrackbarPos("B", "image");

    Mat& img = *(cv::Mat*)param;
    if (event == EVENT_LBUTTONDOWN)
    {
        drawing = true;
        ix = x;
        iy = y;
    }
    if (event == EVENT_MOUSEMOVE)
    {
        if (drawing)
        {
            if (mode)
            {
                rectangle(img, Point(ix, iy), Point(x, y), Scalar(b, g, r), -1);
            }
            else
            {
                // 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
                circle(img, Point(x, y), 3, Scalar(b, g, r), -1);

                //下面注释掉的代码是起始点为圆心,起点到终点为半径的
                //int r = (int)(Math.Sqrt((x - ix) * (x - ix) + (y - iy) * (y - iy)));
                //circle(img, new Point(x, y), r, Scalar(b, g, r), -1);
            }
        }
    }
    // 当鼠标松开停止绘画。
    if (event == EVENT_LBUTTONUP)
    {
        drawing = false;
    }
}

void main()
{
    Mat img(512, 512, CV_8UC3);
    namedWindow("image");
    createTrackbar("R", "image", NULL, 255);
    createTrackbar("G", "image", NULL, 255);
    createTrackbar("B", "image", NULL, 255);

    setMouseCallback("image", on_MouseHandle, (void*)&img);
    while (true)
    {
        imshow("image", img);
        if (waitKey(1) == 'm')
        {
            mode = !mode;
        }
    }
}
#endif

// 调节画布颜色
#if DEMOID == 1
void main()
{
    string swit = "0 : OFF \n1 : ON";
    Mat img(300, 512, CV_8UC3);
    namedWindow("image");
    createTrackbar("R", "image", NULL, 255);
    createTrackbar("G", "image", NULL, 255);
    createTrackbar("B", "image", NULL, 255);
    createTrackbar(swit, "image", NULL, 1);

    while (true)
    {
        int r = getTrackbarPos("R", "image");
        int g = getTrackbarPos("G", "image");
        int b = getTrackbarPos("B", "image");
        int s = getTrackbarPos(swit, "image");

        if (s == 0)
            img = Scalar::all(0);
        else
            img = Scalar(b, g, r);

        imshow("image", img);
        waitKey(1);
    }
}
#endif


Python版本运行效果及代码如下:

demo1:绘制不同颜色的圆和矩形演示效果和代码如下:

# -*- coding: utf-8 -*-
import cv2
import numpy as np

def nothing(x):
    pass

# 当鼠标按下时变为 True
drawing = False
# 如果 mode 为 true 绘制矩形。按下'm' 变成绘制曲线。 mode=True
ix, iy = -1, -1

'''
cv2.getTrackbarPos() 函数的第一个参数是滑动条的名字 
第二个参数 是滑动条被放置窗口的名字 
第三个参数是滑动条的默认位置。
第四个参数是滑动条的最大值 
第五个函数是回调函数, 每次滑动条的滑动都会调用回调函 数。
回调函数通常都会含有一个默认参数 就是滑动条的位置
'''

# 创建回调函数
def 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)

    global ix, iy, drawing, mode
    # 当按下左键是返回起始位置坐标
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    # 当鼠标左键按下并移动是绘制图形。event 可以查看移动,flag 查看是否按下
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing is True:
            if mode is True:
                cv2.rectangle(img, (ix, iy), (x, y), color, -1)
            else:
                # 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
                cv2.circle(img, (x, y), 3, color, -1)
                # 下面注释掉的代码是起始点为圆心,起点到终点为半径的
                # r=int(np.sqrt((x-ix)**2+(y-iy)**2))
                # cv2.circle(img,(x,y),r,(0,0,255),-1)

                # 当鼠标松开停止绘画。
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        # if mode==True:
        #     cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
        # else:
        #     cv2.circle(img,(x,y),5,(0,0,255),-1)

img = np.zeros((512, 512, 3), np.uint8)
mode = False

cv2.namedWindow('image')
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
cv2.setMouseCallback('image', draw_circle)

while True:
    cv2.imshow('image', img)
    k = cv2.waitKey(1)  # & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == ord("q"):
        break


demo2:调节画布颜色演示效果和代码如下:

# -*- coding: utf-8 -*-

import cv2
import numpy as np


def nothing(x):
    pass


# Create a black image, a window
img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)

# 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
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image', 0, 1, nothing)
# 只有当 转换按钮 指向 ON 时 滑动条的滑动才有用,否则窗户 都是黑的。

while True:

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R', 'image')
    g = cv2.getTrackbarPos('G', 'image')
    b = cv2.getTrackbarPos('B', 'image')
    s = cv2.getTrackbarPos(switch, 'image')  # 另外一个重要应用就是用作转换按钮

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b, g, r]

    cv2.imshow('image', img)
    k = cv2.waitKey(1)  # & 0xFF
    if k == ord("q"):
        break

cv2.destroyAllWindows()


把鼠标当画笔
图像的基础操作

友情链接: CSDN激萌の小宅 95知识库 自考题库 罗分明个人网络博客 精益编程leanboot

小宅博客  www.bilibili996.com All Rights Reserved. 备案号: 闽ICP备2024034575号

网站经营许可证  福建省福州市 Copyright©2021-2025 版权所有

小宅博客
首页 智能家居 地图定位
公告:小宅博客网可以开发票了,需要发票的,去群里找群主哈!!

文章作者:激萌の小宅

促销:¥0

价格:¥0

配送方式: 购买后立即生效(如购买异常,请联系站长)
付款之后一定要等待自动跳转结束,否则购买可能会失败
  • 0 天

    有效期

  • 0

    总销量

  • 0

    累计评价

用滑动条做调色板

当前系列所有demo下载地址:

https://github.com/GaoRenBao/OpenCv4-Demo

不同编程语言对应的OpenCv版本以及开发环境信息如下: 

语言

OpenCv版本

IDE

C#

OpenCvSharp4.4.8.0.20230708

Visual Studio 2022

C++

OpenCv-4.5.5-vc14_vc15

Visual Studio 2022

Python

OpenCv-Python (4.6.0.66)

PyCharm Community Edition 2022.1.3


当前章节共2个demo

demo1:绘制不同颜色的圆和矩形

1.gif


demo2:调节画布颜色

1 (1).gif


C#版本运行代码如下:

demo1:绘制不同颜色的圆和矩形演示代码如下:

using OpenCvSharp;
using System;

namespace ConsoleApp
{
  internal class Program
  {
    public static Mat img = new Mat();
    // 矩形和圆形模式切换
    public static bool mode = false;
    public static bool drawing = false;
    public static int ix = -1, iy = -1;
    public static void draw_circle(MouseEventTypes @event, int x, int y, MouseEventFlags flags, IntPtr userData)
    {
      int r = Cv2.GetTrackbarPos("R", "image");
      int g = Cv2.GetTrackbarPos("G", "image");
      int b = Cv2.GetTrackbarPos("B", "image");

      // 当按下左键是返回起始位置坐标
      if (@event == MouseEventTypes.LButtonDown)
      {
        drawing = true;
        ix = x;
        iy = y;
      }
      if (@event == MouseEventTypes.MouseMove)
      {
        if(drawing)
        {
          if (mode)
          {
            Cv2.Rectangle(img, new Point(ix, iy), new Point(x, y), new Scalar(b, g, r), -1);
          }
          else
          {
            // 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
            Cv2.Circle(img, new Point(x, y), 3, new Scalar(b, g, r), -1);

            //下面注释掉的代码是起始点为圆心,起点到终点为半径的
            //int r = (int)(Math.Sqrt((x - ix) * (x - ix) + (y - iy) * (y - iy)));
            //Cv2.Circle(img, new Point(x, y), r, new Scalar(b, g, r), -1);
          }
        } 
      }
      // 当鼠标松开停止绘画。
      if (@event == MouseEventTypes.LButtonUp)
      {
        drawing = false;
      }
    }

    public static void Main(string[] args)
    {
      img = new Mat(new Size(512, 512), MatType.CV_8UC3, new Scalar(0, 0, 0));
      Cv2.NamedWindow("image", WindowFlags.AutoSize);

      Cv2.CreateTrackbar("R", "image", 255, null);
      Cv2.CreateTrackbar("G", "image", 255, null);
      Cv2.CreateTrackbar("B", "image", 255, null);
      Cv2.SetMouseCallback("image", new MouseCallback(draw_circle));
      while (true)
      {
        Cv2.ImShow("image", img);
        if (Cv2.WaitKey(1) == 'm')
        {
          mode = !mode;
        }
      }
    }
  }
}


demo2:调节画布颜色,演示代码如下:

using OpenCvSharp;

namespace ConsoleApp
{
  internal class Program
  {
    public static void Main(string[] args)
    {
      string swit = "0 : OFF \n1 : ON";
      Mat img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(0, 0, 0));
      Cv2.NamedWindow("image", WindowFlags.AutoSize);

      Cv2.CreateTrackbar("R", "image", 255, null);
      Cv2.CreateTrackbar("G", "image", 255, null);
      Cv2.CreateTrackbar("B", "image", 255, null);
      Cv2.CreateTrackbar(swit, "image", 1, null);

      while (true)
      {
        int r = Cv2.GetTrackbarPos("R", "image");
        int g = Cv2.GetTrackbarPos("G", "image");
        int b = Cv2.GetTrackbarPos("B", "image");
        int s = Cv2.GetTrackbarPos(swit, "image");

        if (s == 0)
          img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(0, 0, 0));
        else
          img = new Mat(new Size(512, 300), MatType.CV_8UC3, new Scalar(b, g, r));

        Cv2.ImShow("image", img);
        Cv2.WaitKey(1);
        img.Dispose();
      }
    }
  }
}


C++版本运行代码如下:

#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <iostream>

using namespace cv;
using namespace std;

#define DEMOID 0

// 绘制不同颜色的圆和矩形演示代码如下
#if DEMOID == 0
// 当鼠标按下时变为 True
bool drawing = false;
// 矩形和圆形模式切换
bool mode = false;
// 如果 mode 为 true 绘制矩形。按下'm' 变成绘制曲线。 mode=True
int ix = -1, iy = -1;

void on_MouseHandle(int event, int x, int y, int flags, void* param)
{
    int r = getTrackbarPos("R", "image");
    int g = getTrackbarPos("G", "image");
    int b = getTrackbarPos("B", "image");

    Mat& img = *(cv::Mat*)param;
    if (event == EVENT_LBUTTONDOWN)
    {
        drawing = true;
        ix = x;
        iy = y;
    }
    if (event == EVENT_MOUSEMOVE)
    {
        if (drawing)
        {
            if (mode)
            {
                rectangle(img, Point(ix, iy), Point(x, y), Scalar(b, g, r), -1);
            }
            else
            {
                // 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
                circle(img, Point(x, y), 3, Scalar(b, g, r), -1);

                //下面注释掉的代码是起始点为圆心,起点到终点为半径的
                //int r = (int)(Math.Sqrt((x - ix) * (x - ix) + (y - iy) * (y - iy)));
                //circle(img, new Point(x, y), r, Scalar(b, g, r), -1);
            }
        }
    }
    // 当鼠标松开停止绘画。
    if (event == EVENT_LBUTTONUP)
    {
        drawing = false;
    }
}

void main()
{
    Mat img(512, 512, CV_8UC3);
    namedWindow("image");
    createTrackbar("R", "image", NULL, 255);
    createTrackbar("G", "image", NULL, 255);
    createTrackbar("B", "image", NULL, 255);

    setMouseCallback("image", on_MouseHandle, (void*)&img);
    while (true)
    {
        imshow("image", img);
        if (waitKey(1) == 'm')
        {
            mode = !mode;
        }
    }
}
#endif

// 调节画布颜色
#if DEMOID == 1
void main()
{
    string swit = "0 : OFF \n1 : ON";
    Mat img(300, 512, CV_8UC3);
    namedWindow("image");
    createTrackbar("R", "image", NULL, 255);
    createTrackbar("G", "image", NULL, 255);
    createTrackbar("B", "image", NULL, 255);
    createTrackbar(swit, "image", NULL, 1);

    while (true)
    {
        int r = getTrackbarPos("R", "image");
        int g = getTrackbarPos("G", "image");
        int b = getTrackbarPos("B", "image");
        int s = getTrackbarPos(swit, "image");

        if (s == 0)
            img = Scalar::all(0);
        else
            img = Scalar(b, g, r);

        imshow("image", img);
        waitKey(1);
    }
}
#endif


Python版本运行效果及代码如下:

demo1:绘制不同颜色的圆和矩形演示效果和代码如下:

# -*- coding: utf-8 -*-
import cv2
import numpy as np

def nothing(x):
    pass

# 当鼠标按下时变为 True
drawing = False
# 如果 mode 为 true 绘制矩形。按下'm' 变成绘制曲线。 mode=True
ix, iy = -1, -1

'''
cv2.getTrackbarPos() 函数的第一个参数是滑动条的名字 
第二个参数 是滑动条被放置窗口的名字 
第三个参数是滑动条的默认位置。
第四个参数是滑动条的最大值 
第五个函数是回调函数, 每次滑动条的滑动都会调用回调函 数。
回调函数通常都会含有一个默认参数 就是滑动条的位置
'''

# 创建回调函数
def 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)

    global ix, iy, drawing, mode
    # 当按下左键是返回起始位置坐标
    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True
        ix, iy = x, y
    # 当鼠标左键按下并移动是绘制图形。event 可以查看移动,flag 查看是否按下
    elif event == cv2.EVENT_MOUSEMOVE and flags == cv2.EVENT_FLAG_LBUTTON:
        if drawing is True:
            if mode is True:
                cv2.rectangle(img, (ix, iy), (x, y), color, -1)
            else:
                # 绘制圆圈,小圆点连在一起就成了线,3 代表了笔画的粗细
                cv2.circle(img, (x, y), 3, color, -1)
                # 下面注释掉的代码是起始点为圆心,起点到终点为半径的
                # r=int(np.sqrt((x-ix)**2+(y-iy)**2))
                # cv2.circle(img,(x,y),r,(0,0,255),-1)

                # 当鼠标松开停止绘画。
    elif event == cv2.EVENT_LBUTTONUP:
        drawing = False
        # if mode==True:
        #     cv2.rectangle(img,(ix,iy),(x,y),(0,255,0),-1)
        # else:
        #     cv2.circle(img,(x,y),5,(0,0,255),-1)

img = np.zeros((512, 512, 3), np.uint8)
mode = False

cv2.namedWindow('image')
cv2.createTrackbar('R', 'image', 0, 255, nothing)
cv2.createTrackbar('G', 'image', 0, 255, nothing)
cv2.createTrackbar('B', 'image', 0, 255, nothing)
cv2.setMouseCallback('image', draw_circle)

while True:
    cv2.imshow('image', img)
    k = cv2.waitKey(1)  # & 0xFF
    if k == ord('m'):
        mode = not mode
    elif k == ord("q"):
        break


demo2:调节画布颜色演示效果和代码如下:

# -*- coding: utf-8 -*-

import cv2
import numpy as np


def nothing(x):
    pass


# Create a black image, a window
img = np.zeros((300, 512, 3), np.uint8)
cv2.namedWindow('image', cv2.WINDOW_NORMAL)

# 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
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image', 0, 1, nothing)
# 只有当 转换按钮 指向 ON 时 滑动条的滑动才有用,否则窗户 都是黑的。

while True:

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R', 'image')
    g = cv2.getTrackbarPos('G', 'image')
    b = cv2.getTrackbarPos('B', 'image')
    s = cv2.getTrackbarPos(switch, 'image')  # 另外一个重要应用就是用作转换按钮

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b, g, r]

    cv2.imshow('image', img)
    k = cv2.waitKey(1)  # & 0xFF
    if k == ord("q"):
        break

cv2.destroyAllWindows()