首页 > 编程语言 >Python opencv 调用摄像头,并允许鼠标绘制两个框

Python opencv 调用摄像头,并允许鼠标绘制两个框

时间:2023-11-27 14:22:46浏览次数:35  
标签:box 鼠标 Python self selected cv2 opencv boxes True

import cv2

# 定义框的类
class BoundingBox:
    def __init__(self, label, x, y):
        self.label = label
        self.x_initial = x
        self.y_initial = y
        self.x = x
        self.y = y
        self.width = 0
        self.height = 0
        self.selected = False
        self.finished = False

    def draw(self, frame):
        cv2.rectangle(frame, (self.x, self.y), (self.x + self.width, self.y + self.height), (0, 255, 0), 2)
        cv2.putText(frame, self.label, (self.x, self.y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

    def contains_point(self, x, y):
        if self.x < self.x + self.width:
            return self.x < x < self.x + self.width and self.y < y < self.y + self.height
        else:
            return self.x + self.width < x < self.x and self.y + self.height < y < self.y

# 定义全局变量来存储框的信息
boxes = []
max_box_count = 2
selected_box = None

# opncv mouse callback
def on_mouse(event, x, y, flags, params):
    global boxes, selected_box

    if event == cv2.EVENT_LBUTTONDOWN:
        if len(boxes) < max_box_count:
            found_selected = False
            for box in boxes:
                if box.contains_point(x, y):
                    box.selected = True
                    selected_box = box
                    found_selected = True
                else:
                    box.selected = False
            
            # if no select box, create new box and select
            if not found_selected:
                new_box = BoundingBox(f'Box {x}', x, y)
                boxes.append(new_box)
                selected_box = new_box
                selected_box.selected = True

        else:
            for box in boxes:
                if box.contains_point(x, y):
                    box.selected = True
                    selected_box = box

    elif event == cv2.EVENT_LBUTTONUP:
        if selected_box:
            selected_box.finished = True

    elif event == cv2.EVENT_RBUTTONDOWN:
        if selected_box:
            boxes.remove(selected_box)
            selected_box = None

    elif event == cv2.EVENT_MOUSEMOVE:
        # if have select box and mouse left button is pressed
        if selected_box and flags & cv2.EVENT_FLAG_LBUTTON and not selected_box.finished: 
            selected_box.width = x - selected_box.x_initial
            selected_box.height = y - selected_box.y_initial
            selected_box.x = selected_box.x_initial
            selected_box.y = selected_box.y_initial

# 打开外置摄像头
cap = cv2.VideoCapture(0)  # 如果有多个摄像头,可能需要尝试不同的索引

# 创建窗口并绑定鼠标事件
cv2.namedWindow('Video')
cv2.setMouseCallback('Video', on_mouse)

while True:
    ret, frame = cap.read()

    # 画出框并显示标签
    for box in boxes:
        box.draw(frame)

    # 显示实时视频
    cv2.imshow('Video', frame)

    # 按下 'q' 键退出循环
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# 释放摄像头并关闭窗口
cap.release()
cv2.destroyAllWindows()

标签:box,鼠标,Python,self,selected,cv2,opencv,boxes,True
From: https://www.cnblogs.com/cokefentas/p/17859127.html

相关文章

  • Python logging 模块 捕获异常,并保存为 logging 文件
    示例一:logging模块简单使用 basicConfig#!/usr/bin/python2.7#-*-coding:utf-8-*-"""@author:tz_zs"""importloggingimporttimeimporttracebackimportsyslogging.basicConfig(level=logging.DEBUG,form......
  • npm下载node-sass包安装失败,需要下python2?
    问题这个问题真的老问题了,今天在跑一个老项目的时候又遇到了。每次遇到都会感慨,这个包真的是是非多啊,解决方案也很简单,不用下python环境,单纯是版本问题查了下网上有挺好的一篇博客:http://www.inspinia.net/a/388314.html?action=onClick里面的报错跟我的一模一样:解决方案......
  • 3、python脚本连接本地mysql数据库读取表数据
    #coding:utf-8frompymysqlimportconnectdata_list=[]#将数据存入数据库conn=connect(host="10.36.128.83",port=20002,database="sthjj_sthj",user="lw_lwc",password=&qu......
  • Python 之 Numpy 框架入门
    NumPy入门目录NumPy基础使用基本数据类型创建基本数组数组属性数组生成zeros、ones、empty数组生成numpy.zerosnumpy.onesnumpy.empty其它说明numpy.randomnumpy.arangenumpy.linspace数组操作数组排序切片索引数组运算符广播规则修改数组......
  • opencv笔记 - 获取图像属性
    学习链接:https://www.bilibili.com/video/BV1De411R77P/?p=6&vd_source=441ed12ec48d03afe294e7c5f663a0d3获取图像属性主要介绍三个属性:形状属性:行、列、通道数像素数目属性图像的数据类型属性形状属性shapeshape可以获取图像的形状,返回包含行数,列数,通道数的元组.灰度图像:返回行数......
  • python语法基础(1)
    输出print(a,b)注释#查看类型typy()数字转换字符串str(100)数字转字符串int("100")float("100") 格式化a=100b=200c="我现在有%s,你欠我%s"%(a,b)%s字符串%d整数%.2f浮点数快速格式化name="小明"age=13score=60.5print(f"姓名{name......
  • Java开发者的Python快速进修指南:网络编程及并发编程
    今天我们将对网络编程和多线程技术进行讲解,这两者的原理大家都已经了解了,因此我们主要关注的是它们的写法区别。虽然这些区别并不是非常明显,但我们之所以将网络编程和多线程一起讲解,是因为在学习Java的socket知识时,我们通常会将它们结合使用,以实现服务器对多个客户端连接的阻塞IO......
  • 【Python】base64模块对图片进行base64编码和解码
    图片的base64编码就是可以将一副图片数据编码成一串字符串,使用该字符串代替图像地址。这样做有什么意义呢?我们知道,我们所看到的网页上的每一个图片,都是需要消耗一个http请求下载而来的。没错,不管如何,图片的下载始终都要向服务器发出请求,要是图片的下载不用向服务器发出请求,而可......
  • Java开发者的Python快速进修指南:自定义模块及常用模块
    好的,按照我们平常的惯例,我先来讲一下今天这节课的内容,以及Java和Python在某些方面的相似之处。Python使用import语句来导入包,而Java也是如此。然而,两者之间的区别在于Python没有类路径的概念,它直接使用.py文件的文件名作为导入路径,并将其余的工作交给Python解释器来扫描和处理。另......
  • Python读取Ansible playbooks返回信息
    一.背景及概要设计当公司管理维护的服务器到达一定规模后,就必然借助远程自动化运维工具,而ansible是其中备选之一。Ansible基于Python开发,集合了众多运维工具(puppet、chef、func、fabric)的优点,实现了批量系统配置、批量程序部署、批量运行命令等功能。Ansible是借助ssh来和远程主机......