420.Count and Say-报数(容易题)

本文介绍了一种名为“报数”的数学序列生成方法,通过解析序列的构成规则,实现了从初始值1开始生成任意第n项的具体算法实现。
部署运行你感兴趣的模型镜像

报数

  1. 题目

    报数指的是,按照其中的整数的顺序进行报数,然后得到下一个数。如下所示:
    1, 11, 21, 1211, 111221, …
    1 读作 “one 1” -> 11.
    11 读作 “two 1s” -> 21.
    21 读作 “one 2, then one 1” -> 1211.
    给定一个整数 n, 返回 第 n 个顺序。

    注意事项
    整数的顺序将表示为一个字符串。

  2. 样例

    给定 n = 5, 返回 “111221”.

  3. 题解

    本题主要难点在于读懂题意,意思是要求我们对字符串中连续相同的子串进行翻译,如:
    1,表示只有1个1,则->11;
    11,连续子串为11,表示有2个1,则->21;
    21,连续子串为2和1,表示有1个2和1个1,则->1211;
    1211,连续子串为1个1,1个2,2个1,表示有1个1、1个2,2个1,则->111221;
    ……
    理解了题意,代码就很简单了,对原始字符串进行遍历,找出连续子串,并用子串的“长度+字符”表示即可。

public class Solution {
    /**
     * @param n the nth
     * @return the nth sequence
     */
    public String countAndSay(int n) {
        String oldString = "1";
        while (--n > 0) 
        {
            StringBuilder sb = new StringBuilder();
            char [] oldChars = oldString.toCharArray();

            for (int i = 0; i < oldChars.length; i++) 
            {
                int count = 1;
                while ((i+1) < oldChars.length && oldChars[i] == oldChars[i+1]) 
                {
                    count++;
                    i++;
                }
                sb.append(String.valueOf(count) + String.valueOf(oldChars[i]));
            }
            oldString = sb.toString();
        }

        return oldString;
    }
}

Last Update 2016.9.16

您可能感兴趣的与本文相关的镜像

Python3.10

Python3.10

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

select t1.stats_date_period ,t1.loan_account_id ,t1.user_id ,t1.active_os_list ,t1.active_platform_name_list ,t1.active_sdk_type_list ,t1.active_device_id_list ,t1.latest_active_os ,t1.latest_active_platform_name ,t1.latest_active_sdk_type ,t1.latest_active_device_id ,t1.latest_active_city ,t1.latest_active_province ,t1.latest_active_country ,t1.login_cnt ,t1.repayment_plan_exposure_cnt ,t1.living_confirmed_photo_click_cnt ,t1.app_launch_cnt ,t1.credit_increase_click_cnt ,t1.contact_from_contacts_cnt ,t1.app_exit_cnt ,t1.coupon_pageview_cnt ,t1.change_bank_card_click_cnt ,t1.delete_account_succ_cnt ,t2.active_os_cnt ,t2.active_platform_name_cnt ,t2.active_sdk_type_list ,t2.active_ip_cnt ,t2.active_device_cnt ,t2.active_city_cnt ,t2.active_province_cnt ,t2.active_country_cnt ,t3.login_method_distribution ,t4.app_launch_hour_distribution ,t5.app_consecutive_launch_days ,t6.bankcard_valid_cnt ,t6.bankcard_invalid_cnt from ( select stats_date_period ,loan_account_id ,user_id ,active_os_list ,active_platform_name_list ,active_sdk_type_list ,active_device_id_list ,count(case when event_code = 'login' then 1 end) as login_cnt ,count(case when event_code = 'repayment_plan_exposure' then 1 end) as repayment_plan_exposure_cnt ,count(case when event_code = 'living_confirmed_photo_click' then 1 end) as living_confirmed_photo_click_cnt ,count(case when event_code = 'app_start' then 1 end) as app_launch_cnt ,count(case when event_code = 'credit_increase_click' then 1 end) as credit_increase_click_cnt ,count(case when event_code = 'contact_from_contacts' then 1 end) as contact_from_contacts_cnt ,count(case when event_code = 'app_end' then 1 end) as app_exit_cnt ,count(case when event_code = 'coupon_pageview' then 1 end) as coupon_pageview_cnt ,count(case when event_code = 'change_bank_card_click' then 1 end) as change_bank_card_click_cnt ,count(case when event_code = 'delete_account_succ' then 1 end) as delete_account_succ_cnt ,max(latest_active_os) as latest_active_os ,max(latest_active_platform_name) as latest_active_platform_name ,max(latest_active_sdk_type) as latest_active_sdk_type ,max(latest_active_device_id) as latest_active_device_id ,max(latest_active_city) as latest_active_city ,max(latest_active_province) as latest_active_province ,max(latest_active_country) as latest_active_country from ( select stats_date_period ,loan_account_id ,user_id ,active_os_list ,active_platform_name_list ,active_sdk_type_list ,active_device_id_list ,event_code ,ip ,created_ts ,created_hour ,city ,province ,country ,event_code ,login_type ,last_value(os) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_os -- 过滤空值 ,last_value(active_platform_name_list) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_platform_name ,last_value(active_sdk_type_list) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_sdk_type ,last_value(active_device_id_list) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_device_id ,last_value(city) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_city ,last_value(province) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_province ,last_value(country) over(partition by user_id order by created_ts asc IGNORE NULLS) as latest_active_country from user_detail ) a group by stats_date_period ,loan_account_id ,user_id ,active_os_list ,active_platform_name_list ,active_sdk_type_list ,active_device_id_list ) t1 left join ( select stats_date_period ,loan_account_id ,user_id ,count(distinct active_os_list) as active_os_cnt ,count(distinct active_platform_name_list) as active_platform_name_cnt ,count(distinct active_sdk_type_list) as active_sdk_type_list ,count(distinct ip) as active_ip_cnt ,count(distinct active_device_id_list) as active_device_cnt ,count(distinct case when city is not null then city end) as active_city_cnt ,count(distinct case when province is not null then province end) as active_province_cnt ,count(distinct case when country is not null then country end) as active_country_cnt from user_detail group by stats_date_period ,loan_account_id ,user_id ) t2 on t1.stats_date_period = t2.stats_date_period and t1.user_id = t2.user_id and t1.loan_account_id = t2.loan_account_id left join -- 登录方式分布 ( select stats_date_period ,loan_account_id ,user_id ,concat(login_type, '', cast(login_type_cnt as string)) as login_method_distribution from ( select stats_date_period ,loan_account_id ,user_id ,login_type ,count(1) as login_type_cnt from user_detail where login_type is not null group by stats_date_period ,loan_account_id ,user_id ,login_type ) a ) t3 on t1.stats_date_period = t3.stats_date_period and t1.user_id = t3.user_id and t1.loan_account_id = t3.loan_account_id left join -- APP启动时间段分布 ( select stats_date_period ,loan_account_id ,user_id ,concat(created_hour, '', cast(login_hour_cnt as string)) as app_launch_hour_distribution from ( select stats_date_period ,loan_account_id ,user_id ,created_hour ,count(1) as login_hour_cnt from user_detail where event_code = 'app_start' group by stats_date_period ,loan_account_id ,user_id ,created_hour ) a ) t4 on t1.stats_date_period = t4.stats_date_period and t1.user_id = t4.user_id and t1.loan_account_id = t4.loan_account_id left join -- 用户最后一次连续登陆天数 ( select user_id ,loan_account_id ,stats_date_period ,consecutive_days as app_consecutive_launch_days from ( select user_id ,loan_account_id ,stats_date_period ,min(dt) as session_start_date -- 连续登陆起始日 ,max(dt) as session_end_date -- 连续会话结束日 ,count(distinct dt) as consecutive_days -- 连续登陆天数 ,max(last_login_dt) as last_login_dt -- 用户在该区间最后一次登录日期 from ( select dt ,stats_date_period ,user_id ,loan_account_id ,cast(dt as int) - row_number() over (partition by user_id, b_stats_date_period order by dt) as session_start -- 连续登陆标识 ,max(dt) over (partition by user_id, b_stats_date_period) as last_login_dt -- 用户在该区间最后一次登录日期 from ( select dt ,user_id ,loan_account_id ,stats_date_period from user_detail where event_code = 'app_start' group by dt ,user_id ,loan_account_id ,stats_date_period ) a ) b group by user_id ,loan_account_id ,stats_date_period ) c where last_login_dt = session_end_date -- 限定最后登陆日期=某次连续登陆最后日期,即可取得最后一次连续登陆的天数(1) ) t5 on t1.stats_date_period = t5.stats_date_period and t1.user_id = t5.user_id and t1.loan_account_id = t5.loan_account_id left join -- 银行卡不同状态绑定数 ( select b_stats_date_period as stats_date_period ,user_id ,count(distinct if(available_status = 'A', account_number, null)) as bankcard_valid_cnt ,count(distinct if(available_status = 'U', account_number, null)) as bankcard_invalid_cnt from ( select case when dt = '20251204' then array('T1','T3','T7','T30') when dt between '20251202' and '20251204' then array('T3','T7','T30') when dt between '20251128' and '20251204' then array('T7','T30') when dt between '20251105' and '20251204' then array('T30') end as stats_date_period ,user_id ,account_number ,available_status from ( select dt ,user_id ,account_number ,available_status ,row_number() over (partition by account_number order by updated_ts desc) as rn from ec_dim.dim_ec_df_loan_bank_account -- 只有最近六天 where dt between '20251105' and '20251204' ) a where rn = 1 -- 取最新状态 ) b LATERAL VIEW explode(stats_date_period) b AS b_stats_date_period group by b_stats_date_period ,user_id ) t6 on t1.stats_date_period = t6.stats_date_period and t1.user_id = t6.user_id 以上是我的sql。帮我查看一下到底哪里缺失了右括号
最新发布
12-06
import cv2 import numpy as np from ultralytics import YOLO from filterpy.kalman import KalmanFilter import time from collections import deque import pyttsx3 import threading from PIL import Image, ImageDraw, ImageFont # --- 配置参数 --- CONFIG = { 'CLASS_NAMES': {2: "轿车", 5: "公交车", 7: "卡车"}, 'MOVING_COLOR': (0, 255, 0), # 正常行驶车辆颜色 (绿色) 'ABNORMAL_COLOR': (0, 0, 255), # 异常状态车辆颜色 (红色) 'CONFIDENCE_THRESHOLD': 0.3, # YOLO检测置信度阈值 'COUNT_LINE_POSITION': 0.6, # 计数线位置(屏幕高度的比例) 'SPEED_CALCULATION_WINDOW_SECONDS': 1.0, # 速度计算时间窗口 'ABNORMAL_SPEED_THRESHOLD_KMH': 20.0, # 异常状态速度阈值 (20 km/h) 'ABNORMAL_DURATION_THRESHOLD': 3.0, # 异常状态持续时间阈值 (3秒) 'FOCAL_LENGTH_PX': 1200, # 焦距(像素) 'REFERENCE_HEIGHTS': { # 各类车辆的实际参考高度(单位:米) 2: 1.5, # 轿车 5: 3.0, # 公交车 7: 3.5 # 卡车 }, 'FONT_PATH': 'simhei.ttf', # 中文字体文件路径 'COUNTING_DIRECTION': 'down' # 计数方向: 'down' 表示车辆向下移动计数, 'up' 表示向上移动计数 } # 中文显示工具类 class ChineseDisplay: def __init__(self, font_path='simhei.ttf', font_size=20): try: self.font = ImageFont.truetype(font_path, font_size) self.large_font = ImageFont.truetype(font_path, 24) self.small_font = ImageFont.truetype(font_path, 18) print(f"成功加载字体: {font_path}") except IOError: print(f"警告: 无法加载字体 {font_path}, 将使用默认字体") self.font = ImageFont.load_default() self.large_font = ImageFont.load_default() self.small_font = ImageFont.load_default() def draw_chinese_text(self, frame, text, position, color=(255, 255, 255), font_size='normal'): img_pil = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) draw = ImageDraw.Draw(img_pil) if font_size == 'large': font = self.large_font elif font_size == 'small': font = self.small_font else: font = self.font draw.text(position, text, font=font, fill=color) return cv2.cvtColor(np.array(img_pil), cv2.COLOR_RGB2BGR) # 语音播报管理器 class VoiceAnnouncer: def __init__(self): self.engine = pyttsx3.init() self.engine.setProperty('rate', 150) self.engine.setProperty('volume', 0.8) self.announced_abnormal = set() self.lock = threading.Lock() def announce_abnormal(self, track_id, vehicle_type, duration): with self.lock: if track_id not in self.announced_abnormal: message = f"检测到车辆 {track_id} 号,{vehicle_type},状态异常" print(f"【语音播报】: {message}") def speak(): try: self.engine.say(message) self.engine.runAndWait() except Exception as e: print(f"语音播报错误: {e}") thread = threading.Thread(target=speak) thread.daemon = True thread.start() self.announced_abnormal.add(track_id) def reset_announcements(self): with self.lock: self.announced_abnormal.clear() # 卡尔曼滤波器初始化 def init_kalman(x, y, fps): kf = KalmanFilter(dim_x=4, dim_z=2) dt = 1.0 / fps kf.F = np.array([[1, 0, dt, 0], [0, 1, 0, dt], [0, 0, 1, 0], [0, 0, 0, 1]]) kf.H = np.array([[1, 0, 0, 0], [0, 1, 0, 0]]) kf.P *= 10.0 kf.R = np.array([[1, 0], [0, 1]]) * 5 kf.Q = np.eye(4) * 0.1 kf.x = np.array([x, y, 0, 0]) return kf # 获取跟踪结果 def get_tracks(image, model): boxes = [] results = model.track(image, persist=True, tracker="./bytetrack.yaml", verbose=False, conf=CONFIG['CONFIDENCE_THRESHOLD'], iou=0.5, classes=[2, 5, 7]) if results[0].boxes.id is None: return boxes result_boxes = results[0].boxes for box in result_boxes: if box.is_track: bbox = box.xyxy.cpu().numpy()[0] cls_id = int(box.cls.cpu().numpy()[0]) track_id = int(box.id.cpu().numpy()[0]) center_x = (bbox[0] + bbox[2]) / 2 center_y = (bbox[1] + bbox[3]) / 2 boxes.append({ 'track_id': track_id, 'cls_id': cls_id, 'bbox': bbox, 'center': (center_x, center_y), 'bottom_center': (center_x, bbox[3]), 'height': bbox[3] - bbox[1] }) return boxes # 绘制速度和状态信息 def draw_vehicle_info(frame, chinese_display, bbox, speed_kmh, is_abnormal, abnormal_duration, cls_id, track_id): x1, y1, x2, y2 = bbox.astype(int) class_name = CONFIG['CLASS_NAMES'].get(cls_id, "车辆") speed_text = f"{speed_kmh:.1f} km/h" if is_abnormal: info_text = f"ID:{track_id} {class_name} {speed_text}" status_text = f"异常状态: {abnormal_duration:.1f}秒" frame = chinese_display.draw_chinese_text( frame, status_text, (x1, y1 - 40), color=CONFIG['ABNORMAL_COLOR'], font_size='small' ) else: info_text = f"ID:{track_id} {class_name} {speed_text}" frame = chinese_display.draw_chinese_text( frame, info_text, (x1, y1 - 15), color=(255, 255, 255), font_size='small' ) return frame # 计算实际距离 def calculate_distance(pixel_height, cls_id): if cls_id not in CONFIG['REFERENCE_HEIGHTS']: return None reference_height = CONFIG['REFERENCE_HEIGHTS'][cls_id] focal_length = CONFIG['FOCAL_LENGTH_PX'] distance = (reference_height * focal_length) / pixel_height return distance # 主函数 def main(source): yolo = YOLO("yolo11n.pt") cap = cv2.VideoCapture(source) if not cap.isOpened(): print("无法打开视频源,请检查路径是否正确") return chinese_display = ChineseDisplay(CONFIG['FONT_PATH']) announcer = VoiceAnnouncer() fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) print(f"视频信息: {frame_width}x{frame_height}, {fps:.1f} FPS") count_line_y = int(frame_height * CONFIG['COUNT_LINE_POSITION']) track_states = {} traffic_stats = { 'total_count': 0, 'car_count': 0, 'bus_count': 0, 'truck_count': 0, 'current_normal': 0, 'current_abnormal': 0 } counted_vehicles = set() speed_window_size = int(CONFIG['SPEED_CALCULATION_WINDOW_SECONDS'] * fps) # 记录未计数的车辆(用于调试) uncounted_vehicles = set() while True: ret, frame = cap.read() if not ret: break current_time = time.time() tracks = get_tracks(frame, yolo) traffic_stats['current_normal'] = 0 traffic_stats['current_abnormal'] = 0 # 绘制计数线 cv2.line(frame, (0, count_line_y), (frame_width, count_line_y), (255, 255, 0), 2) frame = chinese_display.draw_chinese_text( frame, f"计数线 ({count_line_y}px)", (10, count_line_y - 15), color=(255, 255, 0), font_size='small' ) for track in tracks: track_id = track['track_id'] cls_id = track['cls_id'] bbox = track['bbox'] center = track['center'] bottom_center = track['bottom_center'] pixel_height = track['height'] x1, y1, x2, y2 = bbox.astype(int) cx, cy = center bx, by = bottom_center # 初始化车辆状态跟踪 if track_id not in track_states: track_states[track_id] = { "kf": init_kalman(cx, cy, fps), "position_history": deque(maxlen=speed_window_size), "height_history": deque(maxlen=speed_window_size), "abnormal_start_time": None, "is_abnormal": False, "counted": False, "last_by": by, # 记录上一帧的底部y坐标 "crossed_line": False # 标记是否已经过线 } # 显示新车辆ID frame = chinese_display.draw_chinese_text( frame, f"新车辆: ID{track_id}", (x1, y1 - 70), color=(0, 255, 255), font_size='small' ) # 卡尔曼滤波更新 kf = track_states[track_id]["kf"] kf.predict() kf.update(np.array([cx, cy])) filtered_center = (kf.x[0], kf.x[1]) # 记录位置和高度历史 pos_history = track_states[track_id]["position_history"] height_history = track_states[track_id]["height_history"] pos_history.append((current_time, filtered_center[0], filtered_center[1], by)) height_history.append((current_time, pixel_height)) # 计算速度 speed_kmh = 0.0 if len(pos_history) >= 2 and len(height_history) >= 2: last_time, last_x, last_y, last_by = pos_history[-1] prev_time, prev_x, prev_y, prev_by = pos_history[0] time_diff = last_time - prev_time if time_diff > 0.1: pixel_dist = np.sqrt((last_x - prev_x) ** 2 + (last_y - prev_y) ** 2) if cls_id in CONFIG['REFERENCE_HEIGHTS'] and pixel_height > 0: last_distance = calculate_distance(height_history[-1][1], cls_id) prev_distance = calculate_distance(height_history[0][1], cls_id) if last_distance is not None and prev_distance is not None: distance_diff = abs(last_distance - prev_distance) speed_mps = distance_diff / time_diff speed_kmh = speed_mps * 3.6 # 检测异常状态 is_abnormal = speed_kmh < CONFIG['ABNORMAL_SPEED_THRESHOLD_KMH'] abnormal_duration = 0.0 abnormal_start_time = track_states[track_id]["abnormal_start_time"] color = (255, 255, 255) if is_abnormal: if abnormal_start_time is None: abnormal_start_time = current_time else: abnormal_duration = current_time - abnormal_start_time if abnormal_duration > CONFIG['ABNORMAL_DURATION_THRESHOLD']: track_states[track_id]["is_abnormal"] = True traffic_stats['current_abnormal'] += 1 color = CONFIG['ABNORMAL_COLOR'] class_name = CONFIG['CLASS_NAMES'].get(cls_id, "车辆") announcer.announce_abnormal(track_id, class_name, abnormal_duration) else: track_states[track_id]["is_abnormal"] = False traffic_stats['current_normal'] += 1 color = (0, 255, 255) else: abnormal_start_time = None track_states[track_id]["is_abnormal"] = False traffic_stats['current_normal'] += 1 color = CONFIG['MOVING_COLOR'] track_states[track_id]["abnormal_start_time"] = abnormal_start_time # === 改进的计数线逻辑 === current_by = by last_by = track_states[track_id]["last_by"] # 判断车辆是否通过计数线 crossed = False if CONFIG['COUNTING_DIRECTION'] == 'down': # 向下移动计数(车辆从屏幕上方进入) if last_by <= count_line_y and current_by > count_line_y: crossed = True else: # 向上移动计数(车辆从屏幕下方进入) if last_by >= count_line_y and current_by < count_line_y: crossed = True # 更新上一帧的底部y坐标 track_states[track_id]["last_by"] = current_by # 如果检测到穿过计数线且未计数 if crossed and not track_states[track_id]["counted"]: track_states[track_id]["counted"] = True track_states[track_id]["crossed_line"] = True counted_vehicles.add(track_id) traffic_stats['total_count'] += 1 if cls_id == 2: traffic_stats['car_count'] += 1 elif cls_id == 5: traffic_stats['bus_count'] += 1 elif cls_id == 7: traffic_stats['truck_count'] += 1 # 显示计数信息 frame = chinese_display.draw_chinese_text( frame, f"计数: ID{track_id}", (x1, y1 - 85), color=(0, 255, 0), font_size='small' ) # 显示计数线判断信息(用于调试) count_status = "已计数" if track_states[track_id]["counted"] else "未计数" frame = chinese_display.draw_chinese_text( frame, f"计数状态: {count_status}", (x1, y1 - 100), color=(200, 200, 255) if not track_states[track_id]["counted"] else (0, 255, 0), font_size='small' ) # 绘制车辆边界框和信息 cv2.rectangle(frame, (x1, y1), (x2, y2), color, 2) frame = draw_vehicle_info( frame, chinese_display, bbox, speed_kmh, track_states[track_id]["is_abnormal"], abnormal_duration, cls_id, track_id ) # 显示距离信息 if cls_id in CONFIG['REFERENCE_HEIGHTS']: distance = calculate_distance(pixel_height, cls_id) if distance is not None: frame = chinese_display.draw_chinese_text( frame, f"距离: {distance:.1f}米", (x1, y1 - 55), color=(200, 200, 255), font_size='small' ) # 显示统计信息 stats_texts = [ f"总车辆: {traffic_stats['total_count']} (轿车: {traffic_stats['car_count']}, 公交: {traffic_stats['bus_count']}, 卡车: {traffic_stats['truck_count']})", f"正常: {traffic_stats['current_normal']} | 异常: {traffic_stats['current_abnormal']}", f"帧率: {fps:.1f} FPS" ] for i, text in enumerate(stats_texts): frame = chinese_display.draw_chinese_text( frame, text, (10, 30 + i * 25), color=(255, 255, 255), font_size='small' ) # 显示状态说明 frame = chinese_display.draw_chinese_text( frame, "绿色: 正常行驶 | 黄色: 低速警告 | 红色: 异常状态", (10, frame_height - 20), color=(255, 255, 255), font_size='small' ) # 显示计数方向 direction_text = f"计数方向: {'向下' if CONFIG['COUNTING_DIRECTION'] == 'down' else '向上'}" frame = chinese_display.draw_chinese_text( frame, direction_text, (frame_width - 200, frame_height - 20), color=(255, 255, 0), font_size='small' ) # 显示计数线位置 count_line_text = f"计数线位置: y={count_line_y}px" frame = chinese_display.draw_chinese_text( frame, count_line_text, (frame_width - 200, frame_height - 50), color=(255, 255, 0), font_size='small' ) cv2.imshow("高速公路车辆状态监测", frame) # 键盘控制 key = cv2.waitKey(1) & 0xFF if key == ord("q"): break elif key == ord(" "): cv2.waitKey(0) elif key == ord("r"): traffic_stats = {k: 0 for k in traffic_stats} counted_vehicles.clear() track_states.clear() announcer.reset_announcements() print("所有计数器和状态已重置") elif key == ord("c"): # 调整计数线位置 CONFIG['COUNT_LINE_POSITION'] += 0.05 if CONFIG['COUNT_LINE_POSITION'] > 0.95: CONFIG['COUNT_LINE_POSITION'] = 0.1 count_line_y = int(frame_height * CONFIG['COUNT_LINE_POSITION']) print(f"计数线位置调整为: {CONFIG['COUNT_LINE_POSITION']} (y={count_line_y}px)") elif key == ord("d"): # 切换计数方向 CONFIG['COUNTING_DIRECTION'] = 'up' if CONFIG['COUNTING_DIRECTION'] == 'down' else 'down' print(f"计数方向调整为: {'向上' if CONFIG['COUNTING_DIRECTION'] == 'up' else '向下'}") # 更新实时帧率 fps = cap.get(cv2.CAP_PROP_FPS) # 释放资源 cap.release() cv2.destroyAllWindows() print("\n=== 最终交通统计 ===") print(f"总车辆数: {traffic_stats['total_count']}") print(f"轿车: {traffic_stats['car_count']}") print(f"公交车: {traffic_stats['bus_count']}") print(f"卡车: {traffic_stats['truck_count']}") print(f"检测到异常状态车辆: {traffic_stats['current_abnormal']}") if __name__ == "__main__": main("video/04-14_14_K287_2795.mp4") 在这段代码的基础下,不再区分上下行,直接统计经过计数线的车辆
11-20
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值