You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用OpenCV检测内部含对角线的旋转盒子轮廓?

问题描述

需要检测图像中盒子的轮廓,部分盒子内部带有对角线。目前无法检测到带对角线的盒子轮廓,尝试过将红色区域转为白色、形态学操作等方法均无效,且图像中的盒子存在旋转情况。

相关代码

def extract_blocks(img, debug_mode: bool = False):

    if debug_mode:
        img = cv2.imread(img)
    
    new_w = 710
    new_h = 710
    img = cv2.resize(img, (new_w, new_h))

    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    gau = cv2.GaussianBlur(gray_img, (5, 5), 0)

    laplacian_gau = cv2.Laplacian(gau,cv2.CV_8U,ksize=5)


    blank = np.ones_like(img) * 255  
    contours, hierarchy = cv2.findContours(laplacian_gau, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)
    print(f"Number of Contours: {len(contours)}")

    blocks = []

    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area < 1900: # Skip too small contour
            continue
        
        rect = cv2.minAreaRect(cnt)
        box = cv2.boxPoints(rect)
        box = np.int32(box)
        w, h = rect[1]  # width, height

        if 50 < min(w, h) < 80 and 50 < max(w, h) < 80:
            blocks.append(box)
            cv2.drawContours(img, [box], 0, (0, 255, 0), 2)
            cv2.drawContours(blank, [box], 0, (0, 0, 255), 2)

    cv2.imshow('laplacian_gau', laplacian_gau)
    cv2.imshow("Detected Blocks", img)
    cv2.imshow("Detected Blocks (White Background)", blank)
    
    cv2.waitKey(0)
    cv2.destroyAllWindows()

内容的提问来源于stack exchange,提问作者Lee Minhyeung

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 07:43:11