利用cv2.line画虚线

找了很久实现画虚线的方法,并没有找到合适的方法,结合cv2.line总结了一个自主可控的画虚线方法,如果有更好的方法也请大家推荐。
代码和示例图如下:

import cv2
import numpy as np


def draw_dashed_line(
    img, line_coord, color=(0, 0, 255), 
    thickness=2, interval=40
):  
    """画虚线

    Args:
        img (numpy array): 原图
        line_coord (list or typle): 直线两端的坐标
        color (tuple, optional): 画线的颜色. Defaults to (0, 0, 255).
        thickness (int, optional): 线的厚度. Defaults to 2.
        interval (int, optional): 间隔. Defaults to 40.
    """
    width_begin, height_begin, width_end, height_end = line_coord
    # 计算宽度和高度的差值
    delta_width = width_end - width_begin
    delta_height = height_end - height_begin
    # 计算斜率
    k = delta_height / delta_width
    # 求反正切
    angle = np.arctan(k)
    distance = np.sqrt(delta_width**2 + delta_height**2)
    cos_angle_value = np.cos(angle)
    sin_angle_value = np.sin(angle)
    # 绘制虚线
    for i in range(0, int(distance), 2*interval):
        draw_begin_width = width_begin + int(i * cos_angle_value)
        draw_begin_height = height_begin + int(i * sin_angle_value)
        draw_end_width = width_begin + int((i + interval) * cos_angle_value)
        draw_end_height = height_begin + int((i + interval) * sin_angle_value)
        cv2.line(
            img, 
            (draw_begin_width, draw_begin_height), 
            (draw_end_width, draw_end_height),
            color, thickness
        )

if __name__ == "__main__":
    img = np.zeros((512, 256, 3), dtype=np.uint8)
    line_coord = [0, 0, img.shape[1] - 1, img.shape[0] - 1]
    draw_dashed_line(img, line_coord, (0, 0, 255), 2, 40)
    dst_image_path = "dashed_line_test.jpg"
    cv2.imwrite(dst_image_path, img)

图1
图2

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐