在 Python OpenCV 中使用 cv2.rectangle 时出现类型错误

问题描述 投票:0回答:1

这是我的代码

colors = [(245,117,16), (117,245,16), (16,117,245)]
def prob_viz(res, actions, input_frame, colors):
    output_frame = input_frame.copy()
    for num, prob in enumerate(res):
        cv2.rectangle(output_frame, (0,60+num*40), (int(prob*100), 90+num*40), colors[num], -1)
        cv2.putText(output_frame, actions[num], (0, 85+num*40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
        
    return output_frame
plt.figure(figsize=(18,18))
plt.imshow(prob_viz(res, actions, image, colors)) 

这是我遇到的错误

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[76], line 10
      8     return output_frame
      9 plt.figure(figsize=(18,18))
---> 10 plt.imshow(prob_viz(res, actions, image, colors))

Cell In[76], line 5, in prob_viz(res, actions, input_frame, colors)
      3 output_frame = input_frame.copy()
      4 for num, prob in enumerate(res):
----> 5     cv2.rectangle(output_frame, (0,60+num*40), (int(prob*100), 90+num*40), colors[num], -1)
      6     cv2.putText(output_frame, actions[num], (0, 85+num*40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255), 2, cv2.LINE_AA)
      8 return output_frame

TypeError: only size-1 arrays can be converted to Python scalars
<Figure size 1800x1800 with 0 Axes>

我期待使用 imshow 显示输出。我尝试将其转换为 int 和 list(map(int) 但没有任何效果,并且我没有得到输出。我的代码有什么问题?请帮我解决这个问题。

res =model.predict(x_test)  
#res is the prediction results of the x_test data using the model i had trained and

actions = np.array(['hello', 'yes', 'no'])
#actions refers to a NumPy array that contains a list of strings for which I have collected training and testing data

image,results = mediapipe_detection(frame,holistic)
#image is a variable used to store the captured frame for training

input_frame is the image being provided to the function 
python python-3.x opencv computer-vision imshow
1个回答
0
投票

我认为,问题是您在此处输入一个数组而不是单个值。因此,您需要在这里更改的是将 prob 更改为单个值。该索引将取决于您如何使用,但我使用零作为例子。

 def prob_viz(res, actions, input_frame, colors):
    output_frame = input_frame.copy()
    for num, prob_array in enumerate(res):
      prob = prob_array[0]  # This index depends on your model output structure
      prob_length = int(prob * 100)
      cv2.rectangle(output_frame, (0, 60 + num * 40), (prob_length, 90 + num * 40), 
      colors[num], -1)
      cv2.putText(output_frame, str(actions[num]), (0, 85 + num * 40), 
      cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
    return output_frame.
© www.soinside.com 2019 - 2024. All rights reserved.