【将图片划分为网格区域并识别坐标点所属网格-适用于简单规则网格】

将图片划分为几个网格区域,根据所给点位坐标,如何识别出所给的坐标在当前图片中所在的网格区域(适用于简单图形)。

#### 需要安装 opencv
$ pip install opencv-python
Python 代码如下
import cv2
import numpy as np


def divide_image_into_grid(image_path, rows, cols):
    # 读取图片
    image = cv2.imread(image_path)
    if image is None:
        print("无法读取图片,请检查图片路径。")
        return

    height, width, _ = image.shape
    print(f"图片宽度: {width}, 图片高度: {height}")

    # 计算每个网格的宽度和高度
    grid_width = width // cols
    grid_height = height // rows
    print(f"网格宽度: {grid_width}, 网格高度: {grid_height}")

    # 绘制网格线
    for i in range(1, rows):
        cv2.line(image, (0, i * grid_height), (width, i * grid_height), (0, 255, 0), 2)
    for j in range(1, cols):
        cv2.line(image, (j * grid_width, 0), (j * grid_width, height), (0, 255, 0), 2)

    # 显示图片
    cv2.imshow('Image with Grid', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return grid_width, grid_height


def get_grid_region(x, y, grid_width, grid_height, rows, cols):
    """
    该函数用于识别特定坐标 (x, y) 所在的网格区域
    :param x: 坐标的 x 值
    :param y: 坐标的 y 值
    :param grid_width: 每个网格的宽度
    :param grid_height: 每个网格的高度
    :param rows: 网格的行数
    :param cols: 网格的列数
    :return: 坐标所在网格的行和列元组 (row, col),若坐标无效则返回 None
    """
    if x < 0 or y < 0 or x >= grid_width * cols or y >= grid_height * rows:
        print("输入的坐标超出图片范围,无效。")
        return None
    col = min(x // grid_width, cols - 1)
    row = min(y // grid_height, rows - 1)
    print(f"计算得到的列索引: {col}, 行索引: {row}")
    return (row, col)


# 示例调用
image_path = 'soccer.jpeg'  # 请替换为你的图片路径
rows = 3
cols = 4

grid_width, grid_height = divide_image_into_grid(image_path, rows, cols)

# 假设要识别的坐标
x = 800
y = 756
print(f"要识别的坐标: ({x}, {y})")
grid = get_grid_region(x, y, grid_width, grid_height, rows, cols)
if grid:
    print(f"坐标 ({x}, {y}) 所在的网格区域:行 {grid[0]}, 列 {grid[1]}")
    
划分效果

在这里插入图片描述

识别区域

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值