MCPcopy Create free account
hub / github.com/BIT-DataLab/Edit-Banana / detect_rectangles_robust

Function detect_rectangles_robust

modules/basic_shape_processor.py:818–1345  ·  view source on GitHub ↗

精准矩形检测(补充SAM3遗漏的矩形) 采用保守策略: - 默认只启用可靠的检测方法(contour, nested_contour) - 提高检测门槛减少误检 - 对检测结果进行内容验证 :param cv2_image: BGR格式的OpenCV图像 :param existing_elements: SAM3已识别的元素字典 :param config: 配置参数字典 :return: {"rectangles": [...], "containers": [...]}

(cv2_image: np.ndarray, existing_elements: dict, config: dict = None)

Source from the content-addressed store, hash-verified

816
817# ======================== CV矩形检测 ========================
818def detect_rectangles_robust(cv2_image: np.ndarray, existing_elements: dict, config: dict = None) -> dict:
819 """
820 精准矩形检测(补充SAM3遗漏的矩形)
821
822 采用保守策略:
823 - 默认只启用可靠的检测方法(contour, nested_contour)
824 - 提高检测门槛减少误检
825 - 对检测结果进行内容验证
826
827 :param cv2_image: BGR格式的OpenCV图像
828 :param existing_elements: SAM3已识别的元素字典
829 :param config: 配置参数字典
830 :return: {"rectangles": [...], "containers": [...]}
831 """
832 default_config = {
833 # 面积限制(提高门槛减少误检)
834 "min_area": 5000, # 提高最小面积(原3000)
835 "min_area_ratio": 0.005, # 最小面积占比
836 "max_area_ratio": 0.5,
837
838 # 去重阈值(更积极去重)
839 "iou_threshold": 0.2, # 降低IoU阈值(原0.3)
840 "nms_threshold": 0.25, # 降低NMS阈值(原0.3)
841
842 # 形状验证(提高要求)
843 "min_rectangularity": 0.7, # 提高矩形度(原0.6)
844 "border_contrast": 15, # 提高边框对比度(原10)
845
846 # 容器检测
847 "container_threshold": 0.8,
848 "min_contained": 3,
849
850 # 启用的检测方法(保守模式:只启用可靠的方法)
851 "enabled_methods": ["contour", "nested_contour"],
852 # 完整模式可用: ["contour", "region", "low_contrast", "hough_lines", "nested_contour"]
853
854 # 内容验证(CV结果需要通过验证)
855 "validate_content": True,
856 "min_content_std": 8, # 内部颜色标准差阈值
857 }
858 cfg = {**default_config, **(config or {})}
859
860 enabled_methods = set(cfg.get("enabled_methods", ["contour", "nested_contour"]))
861
862 h, w = cv2_image.shape[:2]
863 total_area = h * w
864 max_area = total_area * cfg["max_area_ratio"]
865 min_area = max(cfg["min_area"], int(total_area * cfg.get("min_area_ratio", 0)))
866
867 # 收集SAM3已检测的bbox
868 sam3_bboxes = []
869 for elem_type, items in existing_elements.items():
870 for item in items:
871 sam3_bboxes.append({"bbox": item["bbox"], "type": elem_type})
872
873 all_candidates = []
874 gray = cv2.cvtColor(cv2_image, cv2.COLOR_BGR2GRAY)
875

Callers 2

_run_cv_detectionMethod · 0.85
process_basic_shapesFunction · 0.85

Calls 3

_merge_nearby_linesFunction · 0.85
_validate_cv_rectangleFunction · 0.85
calculate_iouFunction · 0.70

Tested by

no test coverage detected