Python OpenCV实现鼠标画框

使用Python+OpenCV实现鼠标画框的代码:

# -*-coding: utf-8 -*-
"""@Project: IntelligentManufacture@File   : user_interaction.py@Author : panjq@E-mail : pan_jinquan@163.com@Date   : 2019-02-21 15:03:18
"""
# -*- coding: utf-8 -*-import cv2
from utils import image_processing
import numpy as np
global img
global point1, point2
global g_rectdef on_mouse(event, x, y, flags, param):global img, point1, point2,g_rectimg2 = img.copy()if event == cv2.EVENT_LBUTTONDOWN:  # 左键点击,则在原图打点print("1-EVENT_LBUTTONDOWN")point1 = (x, y)cv2.circle(img2, point1, 10, (0, 255, 0), 5)cv2.imshow('image', img2)elif event == cv2.EVENT_MOUSEMOVE and (flags & cv2.EVENT_FLAG_LBUTTON):  # 按住左键拖曳,画框print("2-EVENT_FLAG_LBUTTON")cv2.rectangle(img2, point1, (x, y), (255, 0, 0), thickness=2)cv2.imshow('image', img2)elif event == cv2.EVENT_LBUTTONUP:  # 左键释放,显示print("3-EVENT_LBUTTONUP")point2 = (x, y)cv2.rectangle(img2, point1, point2, (0, 0, 255), thickness=2)cv2.imshow('image', img2)if point1!=point2:min_x = min(point1[0], point2[0])min_y = min(point1[1], point2[1])width = abs(point1[0] - point2[0])height = abs(point1[1] - point2[1])g_rect=[min_x,min_y,width,height]cut_img = img[min_y:min_y + height, min_x:min_x + width]cv2.imshow('ROI', cut_img)def get_image_roi(rgb_image):'''获得用户ROI区域的rect=[x,y,w,h]:param rgb_image::return:'''bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)global imgimg=bgr_imagecv2.namedWindow('image')while True:cv2.setMouseCallback('image', on_mouse)# cv2.startWindowThread()  # 加在这个位置cv2.imshow('image', img)key=cv2.waitKey(0)if key==13 or key==32:#按空格和回车键退出breakcv2.destroyAllWindows()img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)return g_rectdef select_user_roi(image_path):'''由于原图的分辨率较大,这里缩小后获取ROI,返回时需要重新scale对应原图:param image_path::return:'''orig_image = image_processing.read_image(image_path)orig_shape = np.shape(orig_image)resize_image = image_processing.resize_image(orig_image, resize_height=800,resize_width=None)re_shape = np.shape(resize_image)g_rect=get_image_roi(resize_image)orgi_rect = image_processing.scale_rect(g_rect, re_shape,orig_shape)roi_image=image_processing.get_rect_image(orig_image,orgi_rect)image_processing.cv_show_image("RECT",roi_image)image_processing.show_image_rect("image",orig_image,orgi_rect)return orgi_rectif __name__ == '__main__':# image_path="../dataset/images/IMG_0007.JPG"image_path="../dataset/test_images/lena.jpg"# rect=get_image_roi(image)rect=select_user_roi(image_path)print(rect)

其中image_processing.py文件如下:

# -*-coding: utf-8 -*-
"""@Project: IntelligentManufacture@File   : image_processing.py@Author : panjq@E-mail : pan_jinquan@163.com@Date   : 2019-02-14 15:34:50
"""import os
import glob
import cv2
import numpy as np
import matplotlib.pyplot as pltdef show_image(title, image):'''调用matplotlib显示RGB图片:param title: 图像标题:param image: 图像的数据:return:'''# plt.figure("show_image")# print(image.dtype)plt.imshow(image)plt.axis('on')  # 关掉坐标轴为 offplt.title(title)  # 图像题目plt.show()def cv_show_image(title, image):'''调用OpenCV显示RGB图片:param title: 图像标题:param image: 输入RGB图像:return:'''channels=image.shape[-1]if channels==3:image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)  # 将BGR转为RGBcv2.imshow(title,image)cv2.waitKey(0)def read_image(filename, resize_height=None, resize_width=None, normalization=False):'''读取图片数据,默认返回的是uint8,[0,255]:param filename::param resize_height::param resize_width::param normalization:是否归一化到[0.,1.0]:return: 返回的RGB图片数据'''bgr_image = cv2.imread(filename)# bgr_image = cv2.imread(filename,cv2.IMREAD_IGNORE_ORIENTATION|cv2.IMREAD_COLOR)if bgr_image is None:print("Warning:不存在:{}", filename)return Noneif len(bgr_image.shape) == 2:  # 若是灰度图则转为三通道print("Warning:gray image", filename)bgr_image = cv2.cvtColor(bgr_image, cv2.COLOR_GRAY2BGR)rgb_image = cv2.cvtColor(bgr_image, cv2.COLOR_BGR2RGB)  # 将BGR转为RGB# show_image(filename,rgb_image)# rgb_image=Image.open(filename)rgb_image = resize_image(rgb_image,resize_height,resize_width)rgb_image = np.asanyarray(rgb_image)if normalization:# 不能写成:rgb_image=rgb_image/255rgb_image = rgb_image / 255.0# show_image("src resize image",image)return rgb_image
def resize_image(image,resize_height, resize_width):''':param image::param resize_height::param resize_width::return:'''image_shape=np.shape(image)height=image_shape[0]width=image_shape[1]if (resize_height is None) and (resize_width is None):#错误写法:resize_height and resize_width is Nonereturn imageif resize_height is None:resize_height=int(height*resize_width/width)elif resize_width is None:resize_width=int(width*resize_height/height)image = cv2.resize(image, dsize=(resize_width, resize_height))return image
def scale_image(image,scale):''':param image::param scale: (scale_w,scale_h):return:'''image = cv2.resize(image,dsize=None, fx=scale[0],fy=scale[1])return imagedef get_rect_image(image,rect):''':param image::param rect: [x,y,w,h]:return:'''x, y, w, h=rectcut_img = image[y:(y+ h),x:(x+w)]return cut_img
def scale_rect(orig_rect,orig_shape,dest_shape):'''对图像进行缩放时,对应的rectangle也要进行缩放:param orig_rect: 原始图像的rect=[x,y,w,h]:param orig_shape: 原始图像的维度shape=[h,w]:param dest_shape: 缩放后图像的维度shape=[h,w]:return: 经过缩放后的rectangle'''new_x=int(orig_rect[0]*dest_shape[1]/orig_shape[1])new_y=int(orig_rect[1]*dest_shape[0]/orig_shape[0])new_w=int(orig_rect[2]*dest_shape[1]/orig_shape[1])new_h=int(orig_rect[3]*dest_shape[0]/orig_shape[0])dest_rect=[new_x,new_y,new_w,new_h]return dest_rectdef show_image_rect(win_name,image,rect):''':param win_name::param image::param rect::return:'''x, y, w, h=rectpoint1=(x,y)point2=(x+w,y+h)cv2.rectangle(image, point1, point2, (0, 0, 255), thickness=2)cv_show_image(win_name, image)def rgb_to_gray(image):image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)return imagedef save_image(image_path, rgb_image,toUINT8=True):if toUINT8:rgb_image = np.asanyarray(rgb_image * 255, dtype=np.uint8)if len(rgb_image.shape) == 2:  # 若是灰度图则转为三通道bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_GRAY2BGR)else:bgr_image = cv2.cvtColor(rgb_image, cv2.COLOR_RGB2BGR)cv2.imwrite(image_path, bgr_image)def combime_save_image(orig_image, dest_image, out_dir,name,prefix):'''命名标准:out_dir/name_prefix.jpg:param orig_image::param dest_image::param image_path::param out_dir::param prefix::return:'''dest_path = os.path.join(out_dir, name + "_"+prefix+".jpg")save_image(dest_path, dest_image)dest_image = np.hstack((orig_image, dest_image))save_image(os.path.join(out_dir, "{}_src_{}.jpg".format(name,prefix)), dest_image)if __name__=="__main__":image_path="../dataset/test_images/src.jpg"image = read_image(image_path, resize_height=None, resize_width=None)image = rgb_to_gray(image)orig_shape=np.shape(image)#shape=(h,w)orig_rect=[50,100,100,200]#x,y,w,hprint("orig_shape:{}".format(orig_shape))show_image_rect("orig",image,orig_rect)dest_image=resize_image(image,resize_height=None,resize_width=200)dest_shape=np.shape(dest_image)print("dest_shape:{}".format(dest_shape))dest_rect=scale_rect(orig_rect, orig_shape, dest_shape)show_image_rect("dest",dest_image,dest_rect)

Python OpenCV实现鼠标画框相关推荐

  1. python opencv 双击鼠标绘制圆

    10-python opencv 双击鼠标绘制圆 10-python opencv 双击鼠标绘制圆 概述 实现过程 引用与创建空图 设置回调函数 回调上述函数 显示图像 源代码 运行结果 参考 概述 ...

  2. Python Opencv 实现鼠标事件(包含一个练习)——事件触发讲解·以及鼠标回调函数的实现

    文章目录 鼠标事件概述 鼠标事件发生的结构 鼠标回调函数的标准格式 opencv下包含的所有事件--包含flag和event(可以看一下,熟悉常见事件范围) 鼠标事件的实现函数 一个完整的鼠标事件由一 ...

  3. python opencv入门 鼠标绘图(4)

    内容来自OpenCV-Python Tutorials 自己翻译整理 目标: 学习如何操作鼠标事件 学习cv2.setMouseCallback()函数 简单样例: 首先创建一个鼠标的回调函数,当鼠标 ...

  4. 使用Python和OpenCV捕获鼠标事件,并裁剪图像

    使用Python和OpenCV捕获鼠标事件,并裁剪图像 1. 效果图 2. 源码 参考 这篇博客将介绍如何使用Python和OpenCV捕获鼠标事件.还演示了如何快速裁剪和提取图像区域,这在为自己的自 ...

  5. Python OpenCV:利用滚动条移动图片,利用鼠标缩放图片

    Python OpenCV:利用滚动条移动图片,利用鼠标缩放图片 一.实现目标 二.实现背景 三.实现方法 四.运行环境 五.运行代码 六.运行结果 七.不足 八.参考 一.实现目标   在OpenC ...

  6. Python+OpenCV实现自动扫雷,挑战扫雷世界记录!

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 本文转载自知乎Artrix https://zhuanlan.zh ...

  7. Python+OpenCV实现自动扫雷,创造属于自己的世界记录!

    点击上方"小白学视觉",选择加"星标"或"置顶" 重磅干货,第一时间送达 本文转载自知乎Artrix https://zhuanlan.zh ...

  8. 简单的python画图代码_python opencv如何实现简易画图板 python opencv实现简易画图板代码...

    python opencv如何实现简易画图板?本篇文章小编给大家分享一下python opencv实现简易画图板代码,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看. 代码如下 ...

  9. python+opencv实现机器视觉基础技术(2)(宽度测量,缺陷检测,医学检测

     本篇博客接着讲解机器视觉的有关技术和知识.包括宽度测量,缺陷检测,医学处理. 一:宽度测量   在传统的自动化生产中,对于尺寸的测量,典型的方法就是千分尺.游标卡尺.塞尺等.而这些测量手段测量精度低 ...

最新文章

  1. iOS开源JSON解析库MJExtension
  2. One-Page AlphaGo --十分钟看懂 AlphaGo 的核心算法!
  3. html5包含inc文件,HTML中include file标签的用法
  4. C ++基础 | 用户输入之cin函数的正规使用_4
  5. Can't create handler inside thread that has not called Looper.prepare()
  6. 百位云计算专家齐聚湖畔大学,阿里云MVP全球闭门会聚焦数字化转型
  7. struts2 - View页面中获取Action的成员变量
  8. uniapp开发App如何引入阿里巴巴矢量库图标
  9. 信息系统项目管理师快速记忆口诀
  10. ipadpro画流程图_流程图制作软件,这款软件让你5分钟就能搞定流程图
  11. PC浏览器、手机浏览器 批量下载网页图片
  12. fydeos 安装linux程序,FydeOS安装教程-电脑系统安装手册
  13. 搭建一个属于自己的服务器,并实现内网穿透(外网访问本地服务器功能)
  14. SpringBoot整合Mybatis_plus学习笔记
  15. vant 动态 粘性布局_使用 position:sticky 实现粘性布局
  16. python自学难吗?零基础学python难吗?
  17. 微信、支付宝个人收款的一种实现思路
  18. discuz3.4安装php,Discuz!X3.4论坛源码下载 及 全新安装教程
  19. win10系统怎么禁用某个程序联网,阻止软件联网
  20. Error Calling Method of a PBNI object 的问题现象及解决方案

热门文章

  1. 关于dismissViewControllerAnimated值得注意的一点(deinit)
  2. start.s中的.balignl 16,0xdeadbeef
  3. ACM主要赛考察内容
  4. java 中不常见的关键字:strictfp,transient
  5. 织梦电脑站手机站伪静态+全套伪静态规则-固定目录版
  6. 解决每次从cmd进入sqlplus,都得重新设置pagesize、linesize的问题
  7. 简单显示分配器的实现
  8. 申请邓白氏编码和公司开发者账号需要的东西
  9. JPA 不在 persistence.xml 文件中配置每个Entity实体类的2种解决办法
  10. POJ 1293 - Duty Free Shop 01背包记录所选物品