将图片划分为几个网格区域,根据所给点位坐标,如何识别出所给的坐标在当前图片中所在的网格区域(适用于简单图形)。
$ 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]}")
划分效果

识别区域
