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

OpenCV将视频帧划分为4区域分别统计车辆数的条件写法问题

问题原因

你的代码存在两个核心错误,导致只能统计到2个分区的车辆:

  1. x轴阈值计算错误:图像x坐标取值范围为0 ~ img.shape[1]-1,你写的第二个判断阈值img.shape[1]/2*3是图像宽度的1.5倍,已经超出整张图的坐标范围,所有检测框只会命中前两个判断分支,car_count3和car_count4永远不会触发累加。
  2. 分区判断维度缺失:如果要划分田字格形式的4个分区(2行2列),必须同时判断水平x坐标和垂直y坐标,你当前代码仅判断x轴位置,无法区分上下分区。
修正方案

田字格4分区(2行2列)实现

先在遍历检测框前提前计算分区分界值,避免循环内重复计算,同时通过x、y双维度判断分区归属:

# 获取图像宽高
img_h, img_w = img.shape[:2]
mid_x = img_w / 2  # 水平方向中线
mid_y = img_h / 2  # 垂直方向中线

# 初始化四个分区计数器:左上、右上、左下、右下
count_tl, count_tr, count_bl, count_br = 0, 0, 0, 0

for (x, y, w, h) in cars:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    # 用检测框中心点判断归属,避免框压在分界线上误判
    center_x = x + w / 2
    center_y = y + h / 2
    
    if center_x < mid_x:
        # 左半区判断上下
        if center_y < mid_y:
            count_tl += 1
        else:
            count_bl += 1
    else:
        # 右半区判断上下
        if center_y < mid_y:
            count_tr += 1
        else:
            count_br += 1

水平4等分竖条分区实现

如果你的需求是把画面沿水平方向等分成4个竖条分区,不需要判断y轴,修正x轴阈值即可:

img_h, img_w = img.shape[:2]
count1, count2, count3, count4 = 0, 0, 0, 0

for (x, y, w, h) in cars:
    cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 2)
    center_x = x + w / 2
    if center_x < img_w / 4:
        count1 += 1
    elif center_x < img_w / 2:
        count2 += 1
    elif center_x < img_w * 3 / 4:
        count3 += 1
    else:
        count4 += 1
优化提示

用检测框中心点判断分区归属,比直接用左上角坐标判断的准确率更高,能避免检测框跨分界线时的统计错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.02 00:12:16