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 collections模块实例讲解
Apr 07 Python
Python实现telnet服务器的方法
Jul 10 Python
python爬取w3shcool的JQuery课程并且保存到本地
Apr 06 Python
Python进阶之递归函数的用法及其示例
Jan 31 Python
浅谈Pytorch中的torch.gather函数的含义
Aug 18 Python
Python使用python-docx读写word文档
Aug 26 Python
python保存log日志,实现用log日志画图
Dec 24 Python
Python eval函数原理及用法解析
Nov 14 Python
Python 多线程之threading 模块的使用
Apr 14 Python
python实现A*寻路算法
Jun 13 Python
python字典的元素访问实例详解
Jul 21 Python
python实现简单的三子棋游戏
Apr 28 Python
Matplotlib绘制条形图的方法你知道吗
Python的代理类实现,控制访问和修改属性的权限你都了解吗
Mar 21 #Python
python的netCDF4批量处理NC格式文件的操作方法
Python&Matlab实现灰狼优化算法的示例代码
Python学习之时间包使用教程详解
Mar 21 #Python
Python数据结构之队列详解
Python学习之os包使用教程详解
You might like
「OVERLORD」动画重要删减!雅儿贝德的背叛?至尊猎杀队结成
2020/04/09 日漫
兼容PHP5的PHP目录管理函数库
2008/07/10 PHP
php用数组返回无限分类的列表数据的代码
2010/08/08 PHP
yii实现图片上传及缩略图生成的方法
2014/12/04 PHP
Yii2配置Nginx伪静态的方法
2017/05/05 PHP
PHP实现QQ、微信和支付宝三合一收款码实例代码
2018/02/19 PHP
PHP设计模式(三)建造者模式Builder实例详解【创建型】
2020/05/02 PHP
Google Map Api和GOOGLE Search Api整合实现代码
2009/07/18 Javascript
jQuery修改class属性和CSS样式整理
2015/01/30 Javascript
js+HTML5实现canvas多种颜色渐变效果的方法
2015/06/05 Javascript
javascript简单实现类似QQ头像弹出效果的方法
2015/08/03 Javascript
Jsonp 关键字详解及json和jsonp的区别,ajax和jsonp的区别
2015/12/30 Javascript
jquery.qtip提示信息插件用法简单实例
2016/06/17 Javascript
你知道setTimeout是如何运行的吗?
2016/08/16 Javascript
JS实现简单的tab切换选项卡效果
2016/09/21 Javascript
微信小程序 MD5加密登录密码详解及实例代码
2017/01/12 Javascript
Vue中定义全局变量与常量的各种方式详解
2017/08/23 Javascript
[01:01:23]完美世界DOTA2联赛PWL S2 Forest vs FTD.C 第一场 11.26
2020/11/30 DOTA
python处理图片之PIL模块简单使用方法
2015/05/11 Python
Python字符串特性及常用字符串方法的简单笔记
2016/01/04 Python
python使用RNN实现文本分类
2018/05/24 Python
python实现名片管理系统项目
2019/04/26 Python
Python 实现数据结构-循环队列的操作方法
2019/07/17 Python
利用python-docx模块写批量生日邀请函
2019/08/26 Python
Python使用matplotlib绘制三维参数曲线操作示例
2019/09/10 Python
Python使用selenium + headless chrome获取网页内容的方法示例
2019/10/16 Python
Python: tkinter窗口屏幕居中,设置窗口最大,最小尺寸实例
2020/03/04 Python
CSS3制作圆角图片和椭圆形图片
2016/07/08 HTML / CSS
英国电子产品购物网站:Tech in the basket
2019/11/08 全球购物
宾馆总经理岗位职责
2014/02/14 职场文书
求职信模板
2014/05/23 职场文书
入党现实表现材料
2014/12/23 职场文书
无犯罪记录证明样本
2015/06/16 职场文书
情人节单身感言
2015/08/03 职场文书
2019预备党员转正申请书模板2篇!
2019/08/07 职场文书
python 学习GCN图卷积神经网络
2022/05/11 Python