如何循环平移cv2.1矩形

2024-10-02 22:24:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我想让算法填充不变大小/间距的矩形,直到输入的任何窗口大小的边缘。因此窗口的大小会改变,但每个网格线/正方形的大小不会改变

当前代码

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()

当我运行这个程序时,我没有得到任何错误,但是带有两行(矩形)的窗口会原封不动地返回

我还尝试使用warphaffine转换,使用vert_line作为src,返回相同的问题,未更改的窗口

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

Tags: importfornplinezeros绘制widthcv2
1条回答
网友
1楼 · 发布于 2024-10-02 22:24:47

我认为最简单的选择是画直线和柱,而不是矩形。为此,您可以尝试以下方法:

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()

enter image description here

虽然它应该适用于您的用例,但它并不是一个真正好看的代码。我100%确信这是可以优化的,您甚至可以修改它以更好地适应您的用例,但基线在这里

相关问题 更多 >