缺少一些详细信息:
-
边界框的格式是什么:
[x1, y1, x2, y2]
或
[x1, y1, width, height]
或者别的什么?
-
边界框中的值是否已调整大小(
224, 224
)还是原始范围?
无论如何,您可以使用下面的函数绘制矩形(您需要根据格式进行选择):
def draw_bboxes(img, bboxes, color=(0, 0, 255), thickness=1):
for bbox in bboxes:
# if [x1, y1, x2, y2]
cv2.rectangle(img, tuple(bbox[:2]), tuple(bbox[-2:]), color, thickness)
# if [x1, y1, width, height]
cv2.rectangle(img, tuple(bbox[:2]), tuple(bbox[:2]+bbox[-2:]), color, thickness)
假设你定义了你的
bboxes
,可以调用函数:
# [...]
screen = np.array(sct.grab(monitor))
draw_bboxes(screen, bboxes)
# [...]
# [...]
screen = cv2.resize(screen, (224,224)).astype(np.float32)/255
draw_bboxes(screen, bboxes)
# [...]
如果进行了一些更改,完整代码将如下所示:
import cv2
import time
import numpy as np
from mss import mss
def draw_bboxes(img, bboxes, color=(0, 0, 255), thickness=1):
for bbox in bboxes:
cv2.rectangle(img, tuple(bbox[:2]), tuple(bbox[:2]+bbox[-2:]), color, thickness)
# bounding boxes
bboxes = [np.array([12, 16, 29, 25]), np.array([5, 5, 38, 35])]
with mss() as sct:
# part of the screen to capture
monitor = {"top": 79, "left": 265, "width": 905, "height": 586}
while "Screen capturing":
# get screen
last_time = time.time()
screen = np.asarray(sct.grab(monitor))
print('loop took {} seconds'.format(time.time()-last_time))
# convert from BGRA --> BGR
screen = cv2.cvtColor(screen, cv2.COLOR_BGRA2BGR)
# resize and draw bboxes
screen = cv2.resize(screen, (224,224))
draw_bboxes(screen, bboxes)
# display
cv2.imshow("OpenCV/Numpy normal", screen)
# Press "q" to quit
if cv2.waitKey(25) & 0xFF == ord("q"):
cv2.destroyAllWindows()
break
输出如下: