import cv2 import numpy as np from Image_Process.Image_Mask_Ground_Truth_Processing import XMLAnnotationProcessor def test_bounding_box_processing_with_mock_data(): # 初始化XML處理器 processor = XMLAnnotationProcessor() # 創建一個測試圖像 (300x300 彩色圖像) test_image = np.ones((300, 300, 3), dtype=np.uint8) * 128 # 灰色背景 # 在圖像中央創建一個彩色區域 test_image[100:200, 100:200, 0] = 255 # 紅色通道 test_image[120:180, 120:180, 1] = 255 # 綠色通道 test_image[140:160, 140:160, 2] = 255 # 藍色通道 # 創建模擬的bounding box數據 mock_bounding_boxes = [ { 'name': 'test_object', 'xmin': 50, 'ymin': 50, 'xmax': 150, 'ymax': 150 }, { 'name': 'test_object2', 'xmin': 200, 'ymin': 200, 'xmax': 250, 'ymax': 250 } ] # 調用draw_bounding_boxes方法 result_image = processor.draw_bounding_boxes(test_image, mock_bounding_boxes) # 顯示處理結果 print(f"原始圖像形狀: {test_image.shape}") print(f"結果圖像形狀: {result_image.shape}") # 檢查圖像是否有非黑色區域(bounding box內的原圖) non_black_pixels = np.sum(result_image > 0) print(f"非黑色像素數量: {non_black_pixels}") # 檢查第一個bounding box區域是否保留了原圖 box1 = result_image[50:150, 50:150] box1_matches = np.array_equal(box1, test_image[50:150, 50:150]) print(f"第一個bounding box區域是否與原圖相同: {box1_matches}") # 檢查框外區域是否為黑色 outside_box = result_image[0:40, 0:40] # 選擇一個框外區域 is_black = np.sum(outside_box) == 0 print(f"框外區域是否為黑色: {is_black}") if non_black_pixels > 0 and box1_matches and is_black: print("測試成功: bounding box內保持原圖,框外變為黑色") else: print("測試失敗") # 保存結果圖像以便查看 cv2.imwrite("test_bounding_box_result.png", result_image) print("已保存結果圖像: test_bounding_box_result.png") if __name__ == "__main__": test_bounding_box_processing_with_mock_data()