Python+OpenCV实现在图像上绘制矩形


Posted in Python onMarch 21, 2022

话不多说,直接上代码

import copy
import cv2
import numpy as np
 
WIN_NAME = 'draw_rect'
 
 
class Rect(object):
    def __init__(self):
        self.tl = (0, 0)
        self.br = (0, 0)
 
    def regularize(self):
        """
        make sure tl = TopLeft point, br = BottomRight point
        """
        pt1 = (min(self.tl[0], self.br[0]), min(self.tl[1], self.br[1]))
        pt2 = (max(self.tl[0], self.br[0]), max(self.tl[1], self.br[1]))
        self.tl = pt1
        self.br = pt2
 
 
class DrawRects(object):
    def __init__(self, image, color, thickness=1):
        self.original_image = image
        self.image_for_show = image.copy()
        self.color = color
        self.thickness = thickness
        self.rects = []
        self.current_rect = Rect()
        self.left_button_down = False
 
    @staticmethod
    def __clip(value, low, high):
        """
        clip value between low and high
        Parameters
        ----------
        value: a number
            value to be clipped
        low: a number
            low limit
        high: a number
            high limit
        Returns
        -------
        output: a number
            clipped value
        """
        output = max(value, low)
        output = min(output, high)
        return output
 
    def shrink_point(self, x, y):
        """
        shrink point (x, y) to inside image_for_show
        Parameters
        ----------
        x, y: int, int
            coordinate of a point
        Returns
        -------
        x_shrink, y_shrink: int, int
            shrinked coordinate
        """
        height, width = self.image_for_show.shape[0:2]
        x_shrink = self.__clip(x, 0, width)
        y_shrink = self.__clip(y, 0, height)
        return (x_shrink, y_shrink)
 
    def append(self):
        """
        add a rect to rects list
        """
        self.rects.append(copy.deepcopy(self.current_rect))
 
    def pop(self):
        """
        pop a rect from rects list
        """
        rect = Rect()
        if self.rects:
            rect = self.rects.pop()
        return rect
 
    def reset_image(self):
        """
        reset image_for_show using original image
        """
        self.image_for_show = self.original_image.copy()
 
    def draw(self):
        """
        draw rects on image_for_show
        """
        for rect in self.rects:
            cv2.rectangle(self.image_for_show, rect.tl, rect.br,
                          color=self.color, thickness=self.thickness)
 
    def draw_current_rect(self):
        """
        draw current rect on image_for_show
        """
        cv2.rectangle(self.image_for_show,
                      self.current_rect.tl, self.current_rect.br,
                      color=self.color, thickness=self.thickness)
 
 
def onmouse_draw_rect(event, x, y, flags, draw_rects):
    if event == cv2.EVENT_LBUTTONDOWN:
        # pick first point of rect
        print('pt1: x = %d, y = %d' % (x, y))
        draw_rects.left_button_down = True
        draw_rects.current_rect.tl = (x, y)
    if draw_rects.left_button_down and event == cv2.EVENT_MOUSEMOVE:
        # pick second point of rect and draw current rect
        draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
        draw_rects.reset_image()
        draw_rects.draw()
        draw_rects.draw_current_rect()
    if event == cv2.EVENT_LBUTTONUP:
        # finish drawing current rect and append it to rects list
        draw_rects.left_button_down = False
        draw_rects.current_rect.br = draw_rects.shrink_point(x, y)
        print('pt2: x = %d, y = %d' % (draw_rects.current_rect.br[0],
                                       draw_rects.current_rect.br[1]))
        draw_rects.current_rect.regularize()
        draw_rects.append()
    if (not draw_rects.left_button_down) and event == cv2.EVENT_RBUTTONDOWN:
        # pop the last rect in rects list
        draw_rects.pop()
        draw_rects.reset_image()
        draw_rects.draw()
 
 
if __name__ == '__main__':
    #image = np.zeros((256, 256, 3), np.uint8)
    image = cv2.imread("111.jpg")
    draw_rects = DrawRects(image, (0, 255, 0), 2)
    cv2.namedWindow(WIN_NAME, 0)
    cv2.setMouseCallback(WIN_NAME, onmouse_draw_rect, draw_rects)
    while True:
        cv2.imshow(WIN_NAME, draw_rects.image_for_show)
        key = cv2.waitKey(30)
        if key == 27:  # ESC
            break
    cv2.destroyAllWindows()

运行效果

Python+OpenCV实现在图像上绘制矩形

补充

当然Python+OpenCV不仅能做到在图像上绘制任意大小矩形,还能实现鼠标点击图像时会显示其坐标值

下面是实现代码

import cv2
import numpy as np
 
img = cv2.imread("111.jpg")
 
 
# print img.shape
 
def on_EVENT_LBUTTONDOWN(event, x, y, flags, param):
    if event == cv2.EVENT_LBUTTONDOWN:
        xy = "%d,%d" % (x, y)
        print
        xy
        cv2.circle(img, (x, y), 1, (255, 0, 0), thickness=-1)
        cv2.putText(img, xy, (x, y), cv2.FONT_HERSHEY_PLAIN,
                    1.0, (255, 255, 255), thickness=1)
        cv2.imshow("image", img)
 
 
cv2.namedWindow("image",cv2.WINDOW_KEEPRATIO)
cv2.setMouseCallback("image", on_EVENT_LBUTTONDOWN)
cv2.imshow("image", img)
 
while (True):
    try:
        cv2.waitKey(100)
    except Exception:
        cv2.destroyWindow("image")
        break
 
cv2.waitKey(0)
cv2.destroyAllWindow()

运行结果:

Python+OpenCV实现在图像上绘制矩形

以上就是Python+OpenCV实现在图像上绘制矩形的详细内容,更多关于Python OpenCV的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
Python列表推导式的使用方法
Nov 21 Python
python文件操作整理汇总
Oct 21 Python
python插入数据到列表的方法
Apr 30 Python
Python写入CSV文件的方法
Jul 08 Python
python 生成器生成杨辉三角的方法(必看)
Apr 10 Python
Python3视频转字符动画的实例代码
Aug 29 Python
使用浏览器访问python写的服务器程序
Oct 10 Python
pytorch AvgPool2d函数使用详解
Jan 03 Python
python实现图像拼接
Mar 05 Python
python连接mongodb数据库操作数据示例
Nov 30 Python
python压包的概念及实例详解
Feb 17 Python
python利用xpath爬取网上数据并存储到django模型中
Feb 26 Python
Matplotlib绘制条形图的方法你知道吗
Python的代理类实现,控制访问和修改属性的权限你都了解吗
Mar 21 #Python
python的netCDF4批量处理NC格式文件的操作方法
Python&Matlab实现灰狼优化算法的示例代码
Python学习之时间包使用教程详解
Mar 21 #Python
Python数据结构之队列详解
Python学习之os包使用教程详解
You might like
php实现替换手机号中间数字为*号及隐藏IP最后几位的方法
2016/11/16 PHP
jQuery 1.2.x 升? 1.3.x 注意事项
2009/05/06 Javascript
DOM下的节点属性和操作小结
2009/05/14 Javascript
Extjs学习笔记之七 布局
2010/01/08 Javascript
奉献给JavaScript初学者的编写开发的七个细节
2011/01/11 Javascript
Jquery弹出窗口插件 LeanModal的使用方法
2012/03/10 Javascript
javascript-表格排序(降序/反序)实现介绍(附图)
2013/05/30 Javascript
jquery滚动条插件jScrollPane的使用介绍
2013/11/08 Javascript
JavaScript避免内存泄露及内存管理技巧
2014/09/05 Javascript
轻松创建nodejs服务器(3):代码模块化
2014/12/18 NodeJs
jQuery插件boxScroll实现图片轮播特效
2015/07/14 Javascript
javascript实现仿百度图片的瀑布流加载效果
2016/04/20 Javascript
JS弹出窗口插件zDialog简单用法示例
2016/06/12 Javascript
vue中渐进过渡效果实现
2016/10/27 Javascript
浅谈angular表单提交中ng-submit的默认使用方法
2018/09/30 Javascript
vue+导航锚点联动-滚动监听和点击平滑滚动跳转实例
2019/11/13 Javascript
在HTML中使用JavaScript的两种方法
2020/12/24 Javascript
[02:05]DOTA2完美大师赛趣味视频之看我表演
2017/11/18 DOTA
[01:46]新英雄登场
2019/09/10 DOTA
python发送邮件的实例代码(支持html、图片、附件)
2013/03/04 Python
Python实现生成随机日期字符串的方法示例
2017/12/25 Python
基于python的多进程共享变量正确打开方式
2018/04/28 Python
Python中实现变量赋值传递时的引用和拷贝方法
2018/04/29 Python
对Python中9种生成新对象的方法总结
2018/05/23 Python
Django自带日志 settings.py文件配置方法
2019/08/30 Python
Python接口自动化系列之unittest结合ddt的使用教程详解
2021/02/23 Python
HTML5拖放效果的实现代码
2016/11/17 HTML / CSS
私有程序集与共享程序集有什么区别
2013/04/05 面试题
中科前程Java笔试题
2016/11/20 面试题
大学生军训自我评价分享
2013/11/09 职场文书
户外婚礼策划方案
2014/02/08 职场文书
酒店开业庆典主持词
2014/03/21 职场文书
在职员工证明书
2014/09/19 职场文书
2014乡镇机关党员个人对照检查材料思想汇报
2014/10/09 职场文书
转变工作作风心得体会
2016/01/23 职场文书
golang 如何通过反射创建新对象
2021/04/28 Golang