寻找矩形顶点

算法背景

项目中遇到一个需求,向给定的一个参考线布局的canvas内拖拽增加一个矩形,需要在鼠标拖动到一个格子内时,自动绘制矩形填满该格子,效果如下:
image.png

算法实现:

interface Point {
    x: number;
    y: number;
}

interface Rectangle {
    topLeft: Point;
    width: number;
    height: number;
}

/**
   * 计算矩形顶点
   * 
   * @param xList Y轴坐标
   * @param yList X轴坐标
   * @param point 鼠标所在点
   * @returns 
   */
function findSurroundingRectangle(horList: number[], verList: number[], point: Point): Rectangle {
    const { x, y } = point;
    
    // 找到左边和右边的x坐标
    const leftX: number | null = horList.filter((hx: number) => hx < x).pop() ?? null;
    const rightX: number | null = horList.find((hx: number) => hx > x) ?? null;

    // 找到上边和下边的y坐标(y轴向下)
    const upperY: number | null = verList.filter((vy: number) => vy < y).pop() ?? null;
    const lowerY: number | null = verList.find((vy: number) => vy > y) ?? null;

    if (leftX === null || rightX === null || upperY === null || lowerY === null) {
        throw new Error("无法找到四个点包围给定的点");
    }

    const width: number = rightX - leftX;
    const height: number = lowerY - upperY;
    const topLeft: Point = { x: leftX, y: upperY };
    
    return { topLeft, width, height };
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在OpenCV中,可以通过使用函数cv2.minAreaRect()来寻找内接矩形。该函数接受一个轮廓作为输入,并返回一个带有中心点坐标、宽度、高度和旋转角度信息的旋转矩形。 首先,我们需要得到轮廓。可以通过使用cv2.findContours()函数从图像中获取轮廓。传入的参数是二值图像,可以通过使用阈值化或其他图像处理方法。 接下来,需要选择一个合适的轮廓。根据应用的需求,可以选择最大的轮廓或其他特定的轮廓。 一旦选择了轮廓,就可以使用cv2.minAreaRect()函数来找到内接矩形。该函数的参数是轮廓,它返回一个带有矩形信息的对象。 最后,可以使用cv2.boxPoints()函数从旋转矩形对象中获取四个顶点的坐标,并将其绘制在图像上。可以使用cv2.drawContours()函数绘制这些顶点。 下面是一个示例代码,演示了如何在图像中寻找内接矩形: ```python import cv2 # 读取图像并转换为灰度图像 image = cv2.imread("image.jpg") gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) # 阈值化处理获取二值图像 _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY) # 查找轮廓 contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) # 选择一个轮廓 contour = contours[0] # 寻找内接矩形 rect = cv2.minAreaRect(contour) # 获取矩形顶点 box = cv2.boxPoints(rect) box = np.int0(box) # 在图像上绘制矩形 cv2.drawContours(image, [box], 0, (0, 255, 0), 2) # 显示图像 cv2.imshow("Image", image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段代码首先读取图像并将其转换为灰度图像。然后使用阈值化处理得到二值图像,并通过调用cv2.findContours()函数获取轮廓。在这里选择了第一个轮廓,并使用cv2.minAreaRect()函数找到内接矩形。最后,使用cv2.drawContours()函数在图像上绘制矩形
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值