如何循环翻译 cv2.rectangle

How to loop translate a cv2.rectangle

我正在使用 cv2.rectangles 尝试在 np.zeros window 上绘制网格。我正在寻找一种使用 for 或 while 循环自动重复绘制这些线(长而粗的矩形)的方法,直到水平线与 window 的底部相交,垂直线与宽度相交。

我希望算法在它们之间填充 size/space 不变的矩形,直到输入的任何 window 大小的边缘。所以 window 会改变大小,但每个网格的大小 line/square 不会。

当前代码。

import cv2
import numpy as np

#create np.zeros window
frame = np.zeros((600,600, 3), np.uint8)
width = frame.shape[0]
height = frame.shape[1]

#starting points for vertical line, #earlier while loop wouldn't let me use'<' with tuples
vertp1y = 25
vertp1x = 0
vertp2y = 35
vertp2x = height

#starting points for horizontal lines
horizp1y = 0
horizp1x = 25
horizp2y = width
horizp2x = 35

#pt1 and pt2 parameters set this way to attempting using as variables in later while loop
vert_line=cv2.rectangle(frame, (vertp1y, vertp1x), (vertp2y, vertp2x), (0,225,0), -1)
horiz_line=cv2.rectangle(frame, (horizp1y, horizp1x), (horizp2y, horizp2x), (0,225,0), -1)

while vertp2y < width:
    vertp1y = vertp1y + 25
    vertp2y = vertp2y + 25
    if vertp2y > width:
        break


cv2.imshow('frame', frame)
cv2.waitKey(0)
cv2.destroyAllWindows()

当我 运行 时,我没有收到任何错误,但是带有两条线(矩形)的 window 返回不变。

我也尝试使用 warpAffine 翻译使用 vert_line 作为 src,同样的问题,未更改 window 返回。

M = np.float32([[-1,0,25], [0,1,0]])
vert_line_2 = cv2.warpAffine(vert_line, M, (frame.shape[1], frame.shape[0]))

我认为最简单的选择是绘制线条和列而不是矩形。为此,您可以尝试这样的操作:

import matplotlib.pyplot as plt
import numpy as np


class BoxesDrawer:
    def __init__(self, box_size: tuple, border_size: int, color: tuple = (0, 255, 0)):
        self.box_size = box_size
        self.half_border_size = int(border_size // 2)
        self.color = color

    def draw_on(self, frame: np.asarray) -> np.asarray:
        self._draw_row(frame)
        self._draw_columns(frame)

        return frame

    def _draw_row(self, frame: np.asarray) -> np.asarray:
        row_size = self.box_size[0]

        index = 0
        while True:
            index += row_size
            if index > frame.shape[0]:
                break

            frame[index - self.half_border_size:index + self.half_border_size, :, :] = self.color
        return frame

    def _draw_columns(self, frame: np.asarray) -> np.asarray:
        column_size = self.box_size[1]

        index = 0
        while True:
            index += column_size
            if index > frame.shape[0]:
                break

            frame[:, index - self.half_border_size:index + self.half_border_size, :] = self.color
        return frame


if __name__ == '__main__':
    frame = np.zeros((224, 224, 3))

    drawer = BoxesDrawer(box_size=(20, 20), border_size=3, color=(0, 255, 0))
    drawer.draw_on(frame)

    plt.figure()
    plt.imshow(frame)
    plt.show()

不是很好看的代码,但它应该适用于您的用例。我 100% 确定这可以优化,您甚至可以修改它以更好地适应您的用例,但基线在这里。