用虚线或虚线的opencv矩形 [英] opencv rectangle with dotted or dashed lines

查看:4935
本文介绍了用虚线或虚线的opencv矩形的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一行代码使用python绑定为opencv:

  cv2.rectangle(img, [1],框[0]),(框[3],框[2]),(255,0,0),4)

在图像 img 上绘制一个红色矩形,其厚度 4 / p>

但是有没有一种方式矩形的线条可以风格化?不太多。只是虚线,或虚线,这是真的。

解决方案

  import cv2 
import numpy as np
def drawline (pt1 [0] -pt2 [0])** 2+(pt1 [1],pt1,pt2,color,thickness = 1,style ='dotted',gap = 20):
dist = ] -pt2 [1])** 2)**。5
pts = []
for i in np.arange(0,dist,gap):
r = i / dist
x = int((pt1 [0] *(1-r)+ pt2 [0] * r)+ 5)
y = int((pt1 [1] *(1-r)+ pt2 [ 1] * r)+。5)
p =(x,y)
pts.append(p)

如果style =='dotted':
p in pts:
cv2.circle(img,p,thickness,color,-1)
else:
s = pts [0]
e = pts [0]
i = 0
for p in pts:
s = e
e = p
如果i%2 == 1:
cv2.line(img,s,e,颜色,厚度)
i + = 1

def drawpoly(img,pts,color,thickness = 1,style ='dotted',):
s = pts [0]
e = pts [0]
pts.append(pts.pop(0))
for p in pts:
s = e
e = p
drawline img,s,e,color,thickness,style)

def drawrect(img,pt1,pt2,color,thickness = 1,style ='dotted'):
pts = [pt1 ,(pt2 [0],pt1 [1]),pt2,(pt1 [0],pt2 [1])]
drawpoly(img,pts,color,thickness,style)
$ b b im = np.zeros((800,800,3),dtype ='uint8')
s =(234,222)
e =(500,700)
drawrect(im,s,e,(0,255,255) ,1,'dotted')

cv2.imshow('im',im)
cv2.waitKey()


I have a line of code here that uses the python binding for opencv:

cv2.rectangle(img, (box[1], box[0]), (box[3], box[2]), (255,0,0), 4)

This draws a red rectangle on image img of thickness 4.

But is there a way the lines of the rectangles can be stylized? Not too much. Just dotted, or dashed, that's it really.

解决方案

import cv2
import numpy as np
def drawline(img,pt1,pt2,color,thickness=1,style='dotted',gap=20):
    dist =((pt1[0]-pt2[0])**2+(pt1[1]-pt2[1])**2)**.5
    pts= []
    for i in  np.arange(0,dist,gap):
        r=i/dist
        x=int((pt1[0]*(1-r)+pt2[0]*r)+.5)
        y=int((pt1[1]*(1-r)+pt2[1]*r)+.5)
        p = (x,y)
        pts.append(p)

    if style=='dotted':
        for p in pts:
            cv2.circle(img,p,thickness,color,-1)
    else:
        s=pts[0]
        e=pts[0]
        i=0
        for p in pts:
            s=e
            e=p
            if i%2==1:
                cv2.line(img,s,e,color,thickness)
            i+=1

def drawpoly(img,pts,color,thickness=1,style='dotted',):
    s=pts[0]
    e=pts[0]
    pts.append(pts.pop(0))
    for p in pts:
        s=e
        e=p
        drawline(img,s,e,color,thickness,style)

def drawrect(img,pt1,pt2,color,thickness=1,style='dotted'):
    pts = [pt1,(pt2[0],pt1[1]),pt2,(pt1[0],pt2[1])] 
    drawpoly(img,pts,color,thickness,style)

im = np.zeros((800,800,3),dtype='uint8')
s=(234,222)
e=(500,700)
drawrect(im,s,e,(0,255,255),1,'dotted')

cv2.imshow('im',im)
cv2.waitKey()      

这篇关于用虚线或虚线的opencv矩形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆