我正在嘗試使用物件檢測制作電機控制系統。我有兩個執行緒,一個用于物件檢測,一個用于 GUI。
這是物件檢測的代碼
#execute object detection model in real time
def tfod_window():
global coordinates, class_name, named_coordinates
category_index = label_map_util.create_category_index_from_labelmap(files['LABELMAP'])
while cap.isOpened():
ret, frame = cap.read()
image_np = np.array(frame)
input_tensor = tf.convert_to_tensor(np.expand_dims(image_np, 0), dtype=tf.float32)
detections = detect_fn(input_tensor)
num_detections = int(detections.pop('num_detections'))
detections = {key: value[0, :num_detections].numpy()
for key, value in detections.items()}
detections['num_detections'] = num_detections
# detection_classes should be ints.
detections['detection_classes'] = detections['detection_classes'].astype(np.int64)
label_id_offset = 1
image_np_with_detections = image_np.copy()
viz_utils.visualize_boxes_and_labels_on_image_array(
image_np_with_detections,
detections['detection_boxes'],
detections['detection_classes'] label_id_offset,
detections['detection_scores'],
category_index,
use_normalized_coordinates=True,
max_boxes_to_draw=5,
min_score_thresh=.8,
agnostic_mode=False)
cv2.imshow('object detection', cv2.resize(image_np_with_detections, (800, 600)))
#get the coordinates of the detection boxes
boxes = detections['detection_boxes']
max_boxes_to_draw = boxes.shape[0]
scores = detections['detection_scores']
min_score_thresh=.8
coordinates=[]
class_name=[]
named_coordinates=[]
for i in range(min(max_boxes_to_draw, boxes.shape[0])):
if scores[i] > min_score_thresh:
class_id = int(detections['detection_classes'][i] 1)
coordinates.append(boxes[i])
class_name.append(category_index[class_id]["name"])
named_coordinates.append({
"box": boxes[i],
"class_name": category_index[class_id]["name"],
})
if cv2.waitKey(10) & 0xFF == ord('q'):
cap.release()
cv2.destroyAllWindows()
break
但是,當我想在另一個執行緒中使用坐標時,它會顯示 '''NameError: name 'class_name' is not defined'''。
另一個執行緒的代碼是
def GUI():
while cap.isOpened():
if len(class_name) > 0:
print(class_name)
t1 = Thread(target=tfod)
t2 = Thread(target=GUI)
t1.start()
t2.start()
請幫忙!!謝謝!!
uj5u.com熱心網友回復:
從評論中:在執行緒嘗試訪問它class_name之前沒有宣告/初始化。t2
您可以將定義的單個初始代碼行class_name放在程式頂部附近,這將避免此錯誤。
對于那些可能看到此頁面的人,錯誤與標題無關,但這里有一篇文章討論了如何在執行緒之間正確共享資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491165.html
