14

我这里有一行代码,它使用了opencv的python绑定:

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

img这会在厚度的图像上绘制一个红色矩形4

但是有没有办法可以对矩形的线条进行风格化?没有太多。只是点缀或虚线,就是这样。

4

4 回答 4

19
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()      
于 2014-11-03T09:34:23.150 回答
7

OpenCV(当前)不支持超出厚度和抗锯齿的线属性。

于 2014-11-01T20:57:19.890 回答
5
  • openCV 是开源库,所以你可以找到绘图的源代码并稍微修改它
  • 您可以使用LineIterator并在几行代码中获得您想要的任何样式

    void lineDot(OutputArray img, const Point& pt1, const Point& pt2, const Scalar& color, const vector<bool>& pattern){
        LineIterator it(img.getMat(), pt1, pt2, LINE_8); // LINE_AA is not supported here
        for(auto i=0; i<it.count; i++, it++){
            if(pattern[i%pattern.size()]){ // use any pattern of any length, dotted is {0,0,1}, dashed is {0,0,0,1,1,1} etc
                (*it)[0] = color.val[0];
                (*it)[1] = color.val[1];
                (*it)[2] = color.val[2];
            }
        }
    }
    
于 2014-11-02T20:33:29.403 回答
-2

尝试这样的事情:

cv::Point P1, P2;

P1.y = 50;
P2.y = 50;

int dot_gap = 50;
int dot_width = 50;

for( int i=0 ; i < in_img.cols; (i = i+d_width) ) {

    P1.x = i;
    P2.x = i + dot_width;
    cv::line(in_img, P1, P2, cv::Scalar(0, 255, 255), 2, cv::LINE_8);
}
于 2019-05-16T11:17:22.297 回答