如何使用cv2.rectangle()创建随机颜色的边界框

7
我正在尝试创建随机颜色,并根据单个人的边界框的不同颜色进行更改。
COLORS = np.random.randint(0, 255, [1000, 3])
def visualize_detection_results(img_np, active_actors, prob_dict):
    score_th = 0.30
    action_th = 0.20

    # copy the original image first
    disp_img = np.copy(img_np)
    H, W, C = img_np.shape
    #for ii in range(len(active_actors)):
    for ii in range(len(active_actors)):
        cur_actor = active_actors[ii]
        actor_id = cur_actor['actor_id']
        cur_act_results = prob_dict[actor_id] if actor_id in prob_dict else []
        try:
            cur_box, cur_score, cur_class = cur_actor['all_boxes'][-16], cur_actor['all_scores'][0], 1
        except IndexError:
            continue

        if cur_score < score_th: 
            continue

        top, left, bottom, right = cur_box


        left = int(W * left)
        right = int(W * right)

        top = int(H * top)
        bottom = int(H * bottom)

        conf = cur_score
        #label = bbox['class_str']
        # label = 'Class_%i' % cur_class
        label = obj.OBJECT_STRINGS[cur_class]['name']
        message = '%s_%i: %% %.2f' % (label, actor_id,conf)
        action_message_list = ["%s:%.3f" % (actres[0][0:7], actres[1]) for actres in cur_act_results if actres[1]>action_th]
        # action_message = " ".join(action_message_list)

        color = COLORS[actor_id] 
        print("######",color) # prints[73   0 234]

        cv2.rectangle(disp_img, (left,top), (right,bottom), color, 3)

        font_size =  max(0.5,(right - left)/50.0/float(len(message)))
        cv2.rectangle(disp_img, (left, top-int(font_size*40)), (right,top), color, -1)
        cv2.putText(disp_img, message, (left, top-12), 0, font_size, (255,255,255)-color, 1)

        #action message writing
        cv2.rectangle(disp_img, (left, top), (right,top+10*len(action_message_list)), color, -1)
        for aa, action_message in enumerate(action_message_list):
            offset = aa*10
            cv2.putText(disp_img, action_message, (left, top+5+offset), 0, 0.5, (255,255,255)-color, 1)

    return disp_img

回溯:

Traceback (most recent call last):
  File "detect_actions.py", line 310, in <module>
    main()
  File "detect_actions.py", line 177, in main
    out_img = visualize_detection_results(tracker.frame_history[-16], tracker.active_actors, prob_dict)
  File "detect_actions.py", line 240, in visualize_detection_results
    cv2.rectangle(disp_img, (left,top), (right,bottom), color, 3)
TypeError: Scalar value for argument 'color' is not numeric

在这种情况下,color数组未被视为数字。我已经在StackOverflow上尝试了一些方法,但它们都没有起作用。我的opencv版本是3.3.0。非常感谢您的建议。谢谢。

color = np.array((np.asscalar(np.int16(color[0])),np.asscalar(np.int16(color[1])),np.asscalar(np.int16(color[2]))))
4个回答

6

要生成随机的BGR值,您可以使用np.random(),然后将其插入到cv2.rectangle()中。

color = list(np.random.random(size=3) * 256)
cv2.rectangle(image, (x, y), (x + w, y + h), color, 4)

以下是使用此输入图像的示例

我们找到轮廓并在每个数字周围画一个随机颜色的矩形

import cv2
import numpy as np

image = cv2.imread('1.png')
gray = 255 - cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

cnts = cv2.findContours(gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    color = list(np.random.random(size=3) * 256)
    cv2.rectangle(image, (x, y), (x + w, y + h), color, 4)

cv2.imshow('image', image)
cv2.imwrite('image.png', image)
cv2.waitKey()

1
通过使用“asscalar”值创建numpy数组,您将重新引入您使用“asscalar”解决的问题。
要将颜色用作变量,以下任一解决方案都可行:
# without numpy
tmp = [30,15,130]
color= (tmp[0],tmp[1],tmp[2])
cv2.rectangle(img,(1,1), (30,30),color,3)
# with numpy
tmp = np.array([30,15,130])
color= (np.asscalar(tmp[0]),np.asscalar(tmp[1]),np.asscalar(tmp[2]))
cv2.rectangle(img,(1,1), (30,30),color,3)
# without array
color= (30,15,130)
cv2.rectangle(img,(1,1), (30,30),color,3)

更具体地说,针对你的代码:你生成颜色作为一个二维数组,但在使用asscalar时没有考虑到这一点。尝试使用以下代码:
COLORS = np.random.randint(0, 255, [10, 3])
actor_id = 2
color= (np.asscalar(COLORS[actor_id][0]),np.asscalar(COLORS[actor_id][1]),np.asscalar(COLORS[actor_id][2]))
cv2.rectangle(img,(1,1), (30,30),color,3)

你尝试过将代码作为示例吗?因为这对我有效。Python 3.7 / openCV 3.4。特别是最后一个,其中“color”是硬编码元组,必须正常工作。 - J.D.
似乎你的问题是关于使用变量来存储颜色。但答案在于颜色是如何生成的。我更新了答案,现在应该可以工作了。 - J.D.

0

例如10个元素

colors = [[random.randint(0, 255) for _ in range(3)] for _ in range(0,10)]

0

以下代码行有效:

COLORS = (np.random.randint(0,255), np.random.randint(0,255), np.random.randint(0,255))

and then pass this to the cv2.rectangle as:

cv2.rectangle(org_img, (xmin,ymin), (xmax, ymax), COLORS, 3)

注意:OpenCV版本:4.1.1,Python 3.6。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接