python_opencv用线段画封闭矩形

def draw_circle(event,x,y,flags,param):
    global ix,iy,drawing,mode,start_x,start_y

    if event == cv2.EVENT_LBUTTONDOWN:
        if drawing == False:
            start_x, start_y = x,y
            ix,iy = x,y
            drawing = True
        elif drawing == True:
            cv2.line(img,(ix,iy),(x,y),(0,255,0),3)
            ix, iy = x, y
        print(drawing)
    elif event == cv2.EVENT_MBUTTONDOWN:
        drawing = False

        cv2.line(img, (ix, iy), (start_x, start_y), (0, 255, 0), 3)
        print(drawing)


    #
    # elif event == cv2.EVENT_RBUTTONUP:
    #     cv2.line(img,(ix,iy),(x,y),(0,255,0),3)
# Next we have to bind this mouse callback function to OpenCV # # window. In the main loop, we should set a keyboard binding for
# key ‘m’ to toggle between rectangle and circle.
img = np.zeros((512,512,3), np.uint8)
cv2.namedWindow('image')
cv2.setMouseCallback('image',draw_circle)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == ord('m'): # 切换模式
        mode = not mode
    elif k == 27:
        break

cv2.destroyAllWindows()
使用OpenCV可以通过以下步骤绘制圆角矩形: 1. 导入OpenCV库:`import cv2` 2. 创建一个空白图像:`img = np.zeros((height, width, 3), np.uint8)` 3. 定义矩形的四个角的坐标:`(x, y)`,`(x+width, y)`,`(x+width, y+height)`,`(x, y+height)` 4. 定义圆角的半径:`radius` 5. 使用`cv2.line()`函数绘制矩形的四条线段,使用`cv2.circle()`函数绘制四个圆弧 6. 返回绘制好的图像 下面是一个绘制圆角矩形的示例代码: ``` python import cv2 import numpy as np def rounded_rectangle(img, pt1, pt2, radius, color, thickness): x1, y1 = pt1 x2, y2 = pt2 cv2.rectangle(img, (x1 + radius, y1), (x2 - radius, y2), color, thickness) cv2.rectangle(img, (x1, y1 + radius), (x2, y2 - radius), color, thickness) cv2.circle(img, (x1+radius, y1+radius), radius, color, thickness) cv2.circle(img, (x2-radius, y1+radius), radius, color, thickness) cv2.circle(img, (x1+radius, y2-radius), radius, color, thickness) cv2.circle(img, (x2-radius, y2-radius), radius, color, thickness) # 创建一个空白图像 img = np.zeros((400, 400, 3), np.uint8) # 绘制圆角矩形 pt1 = (50, 50) pt2 = (350, 350) radius = 30 color = (255, 0, 0) thickness = 5 rounded_rectangle(img, pt1, pt2, radius, color, thickness) # 显示图像 cv2.imshow('image', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在这个示例中,我们使用`rounded_rectangle()`函数绘制了一个圆角矩形。函数的参数包括图像、矩形的两个对角点、圆角半径、颜色和线条粗细。最终的结果将在窗口中显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

城墙郭外斜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值