Как правильно разбить рабочее пространство на n x m ячеек

У меня есть этот входное изображение, и я хочу разбить его на ячейки 22 x 10, чтобы позже определить цвет блоков.

Как правильно разбить рабочее пространство на n x m ячеек

Когда я попытался повторно использовать этот отвечать, который отлично работал для рабочей области 4 x 4, я получил неправильную сетку:

Как правильно разбить рабочее пространство на n x m ячеек

Note that this dynamic approach is necessary, as I might have a different number of cells, resolution, etc...

Не могли бы вы сказать мне, что не так с моей модификацией исходного решения? заранее спасибо.

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import numpy as np
import cv2


def gridWorkspace(roi, gridSize=(10, 22), verbose=True):
    """
    Function: gridWorkspace, to find the contours of the red markers.
    ---
    Parameters:
    @param: roi, nd array, cropped region of interest.
    @param: gridSize, tuple, lenght/width or the Workspace.
    @param: verbose, boolean, to show the output of the function. 
    ---
    @return: cellList, list, cells coordinates list,
            cellCenters, list, cells centers list.
    """
    # Store a deep copy for results:
    roi_copy = roi.copy()

    # Divide the image into a grid:
    verticalCells   = gridSize[1]
    horizontalCells = gridSize[0]

    # Cell dimensions
    bigRectWidth  =  roi.shape[1] 
    bigRectHeight =  roi.shape[0]

    cellWidth = bigRectWidth // verticalCells
    cellHeight = bigRectHeight // horizontalCells

    # Store the cells here:
    cellList = []

    # Store cell centers here:
    cellCenters = []

    # Loop thru vertical dimension:
    for j in range(verticalCells):

        # Cell starting y position:
        yo = j * cellHeight

        # Loop thru horizontal dimension:
        for i in range(horizontalCells):

            # Cell starting x position:
            xo = i * cellWidth

            # Cell Dimensions:
            cX = int(xo)
            cY = int(yo)

            # Crop current cell:
            currentCell = roi[cY:cY + cellHeight, cX:cX + cellWidth]

            # into the cell list:
            cellList.append(currentCell)

            # Store cell center:
            cellCenters.append((cX + 0.5 * cellWidth, cY + 0.5 * cellHeight))

            # Draw Cell
            cv2.rectangle(roi_copy, (cX, cY), (cX + cellWidth, cY + cellHeight), (100, 100, 255), 1)

    # Visualize results
    if (verbose):
        cv2.namedWindow("Grid", cv2.WINDOW_NORMAL)
        cv2.imshow("Grid", roi_copy)
        cv2.waitKey(0)

    return cellList, cellCenters

roi = cv2.imread("DsUYY.png")
res = gridWorkspace(roi)
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
0
0
25
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

дважды проверьте вертикальные ячейки, горизонтальные ячейки и размер сетки [индекс]!!

#!/usr/bin/python3
# -*- coding: utf-8 -*-

import numpy as np
import cv2


def gridWorkspace(roi, gridSize=(22, 10), verbose=True):
    """
    Function: gridWorkspace, to find the contours of the red markers.
    ---
    Parameters:
    @param: roi, nd array, cropped region of interest.
    @param: gridSize, tuple, lenght/width or the Workspace.
    @param: verbose, boolean, to show the output of the function. 
    ---
    @return: cellList, list, cells coordinates list,
            cellCenters, list, cells centers list.
    """
    # Store a deep copy for results:
    roi_copy = roi.copy()

    # Divide the image into a grid:
    verticalCells   = gridSize[1]
    horizontalCells = gridSize[0]

    # Cell dimensions
    bigRectWidth  =  roi.shape[1] 
    bigRectHeight =  roi.shape[0]

    cellWidth = bigRectWidth // horizontalCells
    cellHeight = bigRectHeight // verticalCells

    # Store the cells here:
    cellList = []

    # Store cell centers here:
    cellCenters = []

    # Loop thru vertical dimension:
    for j in range(verticalCells):

        # Cell starting y position:
        yo = j * cellHeight

        # Loop thru horizontal dimension:
        for i in range(horizontalCells):

            # Cell starting x position:
            xo = i * cellWidth

            # Cell Dimensions:
            cX = int(xo)
            cY = int(yo)

            # Crop current cell:
            currentCell = roi[cY:cY + cellHeight, cX:cX + cellWidth]

            # into the cell list:
            cellList.append(currentCell)

            # Store cell center:
            cellCenters.append((cX + 0.5 * cellWidth, cY + 0.5 * cellHeight))

            # Draw Cell
            cv2.rectangle(roi_copy, (cX, cY), (cX + cellWidth, cY + cellHeight), (100, 100, 255), 1)

    # Visualize results
    if (verbose):
        cv2.namedWindow("Grid", cv2.WINDOW_NORMAL)
        cv2.imshow("Grid", roi_copy)
        cv2.waitKey(0)

    return cellList, cellCenters

roi = cv2.imread("/Users/buenos/buenos/playground/python/assets/DsUYY.png")
res = gridWorkspace(roi)

Другие вопросы по теме