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中的编码知识整理汇总
Jan 26 Python
python OpenCV学习笔记实现二维直方图
Feb 08 Python
opencv python 2D直方图的示例代码
Jul 20 Python
Numpy中的mask的使用
Jul 21 Python
Python 确定多项式拟合/回归的阶数实例
Dec 29 Python
在Python文件中指定Python解释器的方法
Feb 18 Python
python自定义线程池控制线程数量的示例
Feb 22 Python
pip 安装库比较慢的解决方法(国内镜像)
Oct 06 Python
解析Python3中的Import
Oct 13 Python
Python爬虫爬取微信朋友圈
Aug 06 Python
Python基于locals返回作用域字典
Oct 17 Python
如何利用python创作字符画
Jun 25 Python
Matplotlib绘制条形图的方法你知道吗
Python的代理类实现,控制访问和修改属性的权限你都了解吗
Mar 21 #Python
python的netCDF4批量处理NC格式文件的操作方法
Python&Matlab实现灰狼优化算法的示例代码
Python学习之时间包使用教程详解
Mar 21 #Python
Python数据结构之队列详解
Python学习之os包使用教程详解
You might like
jQuery获取json后使用zy_tmpl生成下拉菜单
2015/03/27 PHP
Symfony2开发之控制器用法实例分析
2016/02/05 PHP
javascript的console.log()用法小结
2012/05/31 Javascript
Jquery实现显示和隐藏的4种简单方式
2013/08/28 Javascript
javascript上传图片前预览图片兼容大多数浏览器
2013/10/25 Javascript
简易的投票系统以及js刷票思路和方法
2015/04/07 Javascript
基于jQuery实现动态数字展示效果
2015/08/12 Javascript
深入分析Javascript事件代理
2016/01/30 Javascript
JavaScript判断数字是否为质数的方法汇总
2016/06/02 Javascript
jQuery简单实现tab选项卡切换效果
2016/06/20 Javascript
基于jQuery实现中英文切换导航条效果
2016/09/18 Javascript
jquery表单插件form使用方法详解
2017/01/20 Javascript
jQuery复合事件结合toggle()方法的用法示例
2017/06/10 jQuery
JavaScript之DOM插入更新删除_动力节点Java学院整理
2017/07/03 Javascript
jQuery Position方法使用和兼容性
2017/08/23 jQuery
jQuery实现简单日期格式化功能示例
2017/09/19 jQuery
浅谈es6语法 (Proxy和Reflect的对比)
2017/10/24 Javascript
vue router动态路由下让每个子路由都是独立组件的解决方案
2018/04/24 Javascript
在Web关闭页面时发送Ajax请求的实现方法
2019/03/07 Javascript
vue路由中前进后退的一些事儿
2019/05/18 Javascript
微信小程序 (地址选择1)--选取搜索地点并显示效果
2019/12/17 Javascript
react结合bootstrap实现评论功能
2020/05/30 Javascript
Python操作MySQL数据库9个实用实例
2015/12/11 Python
python清理子进程机制剖析
2017/11/23 Python
Python基本数据结构与用法详解【列表、元组、集合、字典】
2019/03/23 Python
python运用sklearn实现KNN分类算法
2019/10/16 Python
基于Python解密仿射密码
2019/10/21 Python
Python爬虫爬取煎蛋网图片代码实例
2019/12/16 Python
Python使用socket_TCP实现小文件下载功能
2020/10/09 Python
html5 canvas的绘制文本自动换行的示例代码
2018/09/17 HTML / CSS
北卡罗来纳州豪华家具和家居装饰店:Carolina Rustica
2018/10/30 全球购物
eDreams加拿大:廉价航班、酒店和度假
2019/03/29 全球购物
职业教育毕业生求职信
2013/11/09 职场文书
自我鉴定怎么写
2013/12/05 职场文书
保安队长职务说明书
2014/02/23 职场文书
SpringBoot集成Redis,并自定义对象序列化操作
2021/06/22 Java/Android