红外弱小目标检测MATLAB程序

简介: 红外弱小目标检测MATLAB程序
%% ==============================================
% 红外弱小目标检测系统
% 功能:包含多种弱小目标检测算法
%% ==============================================

clear all; close all; clc;

%% 1. 读取并显示原始红外图像
% 您可以使用自己的红外图像,这里我们生成一个模拟的红外图像
disp('正在生成模拟红外图像...');
img = generateSimulatedIRImage();
original_img = img;

figure('Name', '原始红外图像', 'Position', [100, 100, 1200, 400]);
subplot(1,3,1);
imshow(original_img, []);
title('原始红外图像');
colorbar;

% 添加直方图均衡化增强显示
subplot(1,3,2);
img_enhanced = histeq(original_img);
imshow(img_enhanced, []);
title('直方图均衡化增强');
colorbar;

% 显示3D表面图
subplot(1,3,3);
[x, y] = meshgrid(1:size(original_img,2), 1:size(original_img,1));
surf(x, y, double(original_img), 'EdgeColor', 'none');
title('红外图像3D表面图');
xlabel('X轴'); ylabel('Y轴'); zlabel('强度');
colormap('hot');
view(-30, 60);

%% 2. 预处理 - 背景抑制
disp('正在进行背景抑制...');
background_suppressed = backgroundSuppression(original_img);

figure('Name', '背景抑制结果', 'Position', [100, 100, 1000, 400]);
subplot(1,2,1);
imshow(original_img, []);
title('原始图像');

subplot(1,2,2);
imshow(background_suppressed, []);
title('背景抑制后图像');
colorbar;

%% 3. 多种目标检测算法
disp('正在使用多种算法进行目标检测...');

% 3.1 Top-Hat滤波
tophat_result = topHatFilter(original_img);

% 3.2 最大中值滤波 (Max-Median)
maxmedian_result = maxMedianFilter(original_img);

% 3.3 局部对比度方法 (LCM)
lcm_result = localContrastMethod(original_img);

% 3.4 改进的局部对比度方法 (ILCM)
ilcm_result = improvedLCM(original_img);

% 3.5 基于梯度加权的方法
gradient_result = gradientWeightedMethod(original_img);

%% 4. 显示所有检测结果
figure('Name', '多种检测算法结果对比', 'Position', [50, 50, 1400, 800]);

% 原始图像
subplot(2,3,1);
imshow(original_img, []);
title('原始红外图像');
colorbar;

% Top-Hat滤波
subplot(2,3,2);
imshow(tophat_result, []);
title('Top-Hat滤波检测结果');
colorbar;

% 最大中值滤波
subplot(2,3,3);
imshow(maxmedian_result, []);
title('最大中值滤波检测结果');
colorbar;

% LCM方法
subplot(2,3,4);
imshow(lcm_result, []);
title('局部对比度方法(LCM)');
colorbar;

% ILCM方法
subplot(2,3,5);
imshow(ilcm_result, []);
title('改进的局部对比度方法(ILCM)');
colorbar;

% 梯度加权方法
subplot(2,3,6);
imshow(gradient_result, []);
title('梯度加权方法');
colorbar;

%% 5. 目标分割与标记
disp('正在进行目标分割与标记...');
threshold_methods = {
   'otsu', 'adaptive', 'percentile'};
segmentation_results = cell(1, length(threshold_methods));

figure('Name', '目标分割结果', 'Position', [100, 100, 1200, 400]);

for i = 1:length(threshold_methods)
    % 使用ILCM结果进行分割(效果较好)
    binary_mask = targetSegmentation(ilcm_result, threshold_methods{
   i});
    segmentation_results{
   i} = binary_mask;

    % 标记目标
    [labeled_img, num_targets] = labelTargets(binary_mask);

    % 显示结果
    subplot(1,3,i);
    imshow(label2rgb(labeled_img, 'jet', 'k', 'shuffle'));
    title(sprintf('%s阈值分割\n检测到%d个目标', ...
        upper(threshold_methods{
   i}), num_targets));

    % 在原图上标记
    figure_temp = figure('Visible', 'off');
    imshow(original_img, []);
    hold on;
    stats = regionprops(labeled_img, 'Centroid', 'BoundingBox');
    for j = 1:length(stats)
        centroid = stats(j).Centroid;
        plot(centroid(1), centroid(2), 'r+', 'MarkerSize', 15, 'LineWidth', 2);
        rectangle('Position', stats(j).BoundingBox, ...
                 'EdgeColor', 'g', 'LineWidth', 2);
    end
    hold off;
    title(sprintf('原始图像上的目标标记 (%s阈值)', upper(threshold_methods{
   i})));

    % 保存图像
    frame = getframe(gcf);
    close(figure_temp);

    figure('Name', sprintf('目标标记结果-%s', upper(threshold_methods{
   i})), ...
           'Position', [100, 100, 800, 600]);
    imshow(frame.cdata);
    title(sprintf('检测到%d个弱小目标', num_targets));
end

%% 6. 性能评估
disp('正在评估检测性能...');
% 假设我们已知目标位置(这里使用模拟目标的真实位置)
[true_targets, ~] = generateSimulatedTargets(size(original_img));

% 评估不同方法
methods = {
   'Top-Hat', 'Max-Median', 'LCM', 'ILCM', 'Gradient'};
results = {
   tophat_result, maxmedian_result, lcm_result, ilcm_result, gradient_result};

figure('Name', '检测性能评估', 'Position', [100, 100, 1000, 600]);

for i = 1:length(methods)
    % 转换为二值图像进行评估
    binary_result = imbinarize(mat2gray(results{
   i}), 'adaptive');

    % 计算检测指标
    metrics = evaluateDetection(binary_result, true_targets);

    % 显示评估结果
    subplot(2,3,i);
    imshow(binary_result);
    title(sprintf('%s方法\n精确度: %.2f%%, 召回率: %.2f%%', ...
        methods{
   i}, metrics.precision*100, metrics.recall*100));

    fprintf('方法: %s\n', methods{
   i});
    fprintf('  精确度: %.2f%%\n', metrics.precision*100);
    fprintf('  召回率: %.2f%%\n', metrics.recall*100);
    fprintf('  F1分数: %.2f%%\n', metrics.f1_score*100);
    fprintf('  虚警率: %.2f%%\n\n', metrics.false_alarm_rate*100);
end

%% 7. 生成检测报告
generateDetectionReport(methods, metrics, num_targets);

disp('红外弱小目标检测完成!');

%% ==============================================
% 辅助函数定义
%% ==============================================

% 生成模拟红外图像
function img = generateSimulatedIRImage()
    % 创建背景(模拟天空或均匀背景)
    [rows, cols] = deal(256);
    background = 100 + 20 * randn(rows, cols);

    % 添加一些云层纹理
    [X, Y] = meshgrid(1:cols, 1:rows);
    cloud_pattern = 15 * sin(0.05*X + 0.1*Y) + 10 * cos(0.03*X + 0.07*Y);
    background = background + cloud_pattern;

    % 添加高斯噪声
    background = background + 5 * randn(rows, cols);

    % 添加弱小目标(小亮点)
    img = background;
    num_targets = randi([3, 8]);  % 随机生成3-8个目标

    for i = 1:num_targets
        % 随机位置
        target_row = randi([20, rows-20]);
        target_col = randi([20, cols-20]);

        % 目标大小(小目标,3x3到5x5像素)
        target_size = randi([2, 3]);

        % 目标强度(比背景高)
        target_intensity = 80 + 40 * rand();

        % 创建高斯形状的目标
        [x, y] = meshgrid(-target_size:target_size, -target_size:target_size);
        gaussian_target = target_intensity * exp(-(x.^2 + y.^2)/(2*(target_size/2)^2));

        % 将目标添加到图像中
        r_start = max(1, target_row-target_size);
        r_end = min(rows, target_row+target_size);
        c_start = max(1, target_col-target_size);
        c_end = min(cols, target_col+target_size);

        target_r_start = target_size - (target_row - r_start) + 1;
        target_r_end = target_size + (r_end - target_row) + 1;
        target_c_start = target_size - (target_col - c_start) + 1;
        target_c_end = target_size + (c_end - target_col) + 1;

        img(r_start:r_end, c_start:c_end) = ...
            img(r_start:r_end, c_start:c_end) + ...
            gaussian_target(target_r_start:target_r_end, target_c_start:target_c_end);
    end

    % 转换为uint8
    img = uint8(mat2gray(img) * 255);
end

% 背景抑制函数
function suppressed_img = backgroundSuppression(img)
    % 使用引导滤波进行背景估计
    img_double = double(img);

    % 引导滤波(保边平滑)
    guided_bg = imguidedfilter(img);

    % 减去背景
    suppressed_img = img_double - double(guided_bg);

    % 增强对比度
    suppressed_img = suppressed_img - min(suppressed_img(:));
    suppressed_img = suppressed_img / max(suppressed_img(:)) * 255;
end

% Top-Hat滤波
function result = topHatFilter(img)
    % 使用形态学Top-Hat滤波增强小目标
    se = strel('disk', 3);  % 结构元素大小根据目标大小调整
    result = imtophat(img, se);
end

% 最大中值滤波
function result = maxMedianFilter(img)
    img_double = double(img);
    [rows, cols] = size(img_double);
    result = zeros(rows, cols);

    % 定义窗口大小
    window_size = 5;
    half_win = floor(window_size/2);

    for i = 1+half_win:rows-half_win
        for j = 1+half_win:cols-half_win
            % 提取局部窗口
            local_window = img_double(i-half_win:i+half_win, j-half_win:j+half_win);

            % 计算中值
            median_val = median(local_window(:));

            % 计算最大值与中值的差
            max_val = max(local_window(:));
            result(i,j) = max_val - median_val;
        end
    end
end

% 局部对比度方法
function result = localContrastMethod(img)
    img_double = double(img);
    [rows, cols] = size(img_double);
    result = zeros(rows, cols);

    % 定义内窗口和外窗口大小
    inner_size = 3;
    outer_size = 9;
    half_outer = floor(outer_size/2);

    for i = 1+half_outer:rows-half_outer
        for j = 1+half_outer:cols-half_outer
            % 内窗口(目标区域)
            inner_region = img_double(i-1:i+1, j-1:j+1);

            % 外窗口(背景区域,排除内窗口)
            outer_region = img_double(i-half_outer:i+half_outer, j-half_outer:j+half_outer);
            outer_region(inner_size:inner_size+2, inner_size:inner_size+2) = NaN;

            % 计算局部对比度
            inner_mean = mean(inner_region(:));
            outer_mean = nanmean(outer_region(:));
            inner_max = max(inner_region(:));

            if outer_mean > 0
                result(i,j) = (inner_max - outer_mean) / outer_mean;
            else
                result(i,j) = 0;
            end
        end
    end
end

% 改进的局部对比度方法
function result = improvedLCM(img)
    img_double = double(img);
    [rows, cols] = size(img_double);
    result = zeros(rows, cols);

    window_size = 9;
    half_win = floor(window_size/2);

    for i = 1+half_win:rows-half_win
        for j = 1+half_win:cols-half_win
            % 提取窗口
            window = img_double(i-half_win:i+half_win, j-half_win:j+half_win);

            % 计算中心像素与周围像素的对比度
            center_val = window(half_win+1, half_win+1);
            surrounding = window;
            surrounding(half_win+1, half_win+1) = NaN;

            % 使用改进的对比度度量
            max_surround = nanmax(surrounding(:));
            min_surround = nanmin(surrounding(:));
            mean_surround = nanmean(surrounding(:));

            if mean_surround > 0
                contrast1 = (center_val - mean_surround) / mean_surround;
                contrast2 = (center_val - min_surround) / (max_surround - min_surround + eps);
                result(i,j) = contrast1 * contrast2;
            else
                result(i,j) = 0;
            end
        end
    end
end

% 梯度加权方法
function result = gradientWeightedMethod(img)
    % 计算梯度幅值
    [Gx, Gy] = imgradientxy(img);
    gradient_mag = sqrt(Gx.^2 + Gy.^2);

    % 归一化梯度
    gradient_norm = mat2gray(gradient_mag);

    % 局部均值
    mean_filter = fspecial('average', 5);
    local_mean = imfilter(double(img), mean_filter);

    % 梯度加权
    result = double(img) .* gradient_norm - local_mean;

    % 移除负值
    result(result < 0) = 0;
end

% 目标分割函数
function binary_mask = targetSegmentation(img, method)
    img_normalized = mat2gray(img);

    switch lower(method)
        case 'otsu'
            level = graythresh(img_normalized);
            binary_mask = imbinarize(img_normalized, level);

        case 'adaptive'
            binary_mask = imbinarize(img_normalized, 'adaptive', ...
                'Sensitivity', 0.6, 'ForegroundPolarity', 'bright');

        case 'percentile'
            % 使用百分比阈值
            sorted_vals = sort(img_normalized(:));
            percentile = 98;  % 取前2%最亮的像素
            idx = round(length(sorted_vals) * percentile / 100);
            threshold = sorted_vals(idx);
            binary_mask = img_normalized > threshold;

        otherwise
            error('未知的阈值方法');
    end

    % 形态学操作去除小噪点
    binary_mask = bwareaopen(binary_mask, 3);  % 移除小于3个像素的区域
    se = strel('disk', 1);
    binary_mask = imclose(binary_mask, se);  # 连接相近的目标
end

% 标记目标函数
function [labeled_img, num_targets] = labelTargets(binary_mask)
    % 连通区域标记
    labeled_img = bwlabel(binary_mask);
    num_targets = max(labeled_img(:));
end

% 评估检测性能函数
function metrics = evaluateDetection(detected, ground_truth)
    % 计算真阳性、假阳性等
    true_positive = sum(detected(:) & ground_truth(:));
    false_positive = sum(detected(:) & ~ground_truth(:));
    false_negative = sum(~detected(:) & ground_truth(:));
    true_negative = sum(~detected(:) & ~ground_truth(:));

    % 计算各项指标
    if (true_positive + false_positive) > 0
        metrics.precision = true_positive / (true_positive + false_positive);
    else
        metrics.precision = 0;
    end

    if (true_positive + false_negative) > 0
        metrics.recall = true_positive / (true_positive + false_negative);
    else
        metrics.recall = 0;
    end

    if (metrics.precision + metrics.recall) > 0
        metrics.f1_score = 2 * metrics.precision * metrics.recall / ...
                          (metrics.precision + metrics.recall);
    else
        metrics.f1_score = 0;
    end

    metrics.false_alarm_rate = false_positive / (false_positive + true_negative);
end

% 生成模拟目标真实位置
function [ground_truth, target_positions] = generateSimulatedTargets(img_size)
    % 这里简单生成一些目标位置
    rows = img_size(1);
    cols = img_size(2);
    ground_truth = false(rows, cols);

    % 生成一些随机目标位置
    num_targets = 5;
    target_positions = zeros(num_targets, 2);

    for i = 1:num_targets
        r = randi([20, rows-20]);
        c = randi([20, cols-20]);
        target_positions(i,:) = [r, c];

        % 在目标位置创建小区域
        ground_truth(r-1:r+1, c-1:c+1) = true;
    end
end

% 生成检测报告
function generateDetectionReport(methods, metrics, num_detected)
    fprintf('\n========== 检测报告 ==========\n');
    fprintf('检测时间: %s\n', datestr(now));
    fprintf('检测到的目标数量: %d\n', num_detected);
    fprintf('\n各方法性能对比:\n');
    fprintf('%-15s %-10s %-10s %-10s\n', '方法', '精确度', '召回率', 'F1分数');
    fprintf('--------------------------------------------\n');

    for i = 1:length(methods)
        fprintf('%-15s %-10.2f %-10.2f %-10.2f\n', ...
            methods{
   i}, metrics(i).precision, metrics(i).recall, metrics(i).f1_score);
    end
    fprintf('==========================================\n\n');

    % 保存报告到文件
    report_filename = sprintf('detection_report_%s.txt', datestr(now, 'yyyymmdd_HHMMSS'));
    fid = fopen(report_filename, 'w');
    if fid ~= -1
        fprintf(fid, '红外弱小目标检测报告\n');
        fprintf(fid, '生成时间: %s\n\n', datestr(now));
        fprintf(fid, '检测统计:\n');
        fprintf(fid, '总检测目标数: %d\n\n', num_detected);
        fclose(fid);
        fprintf('检测报告已保存到: %s\n', report_filename);
    end
end

程序功能说明

1. 主要特点

  • 包含5种弱小目标检测算法
  • 完整的预处理和背景抑制
  • 多种分割阈值方法
  • 性能评估和可视化
  • 自动生成检测报告

2. 包含的算法

  • Top-Hat滤波:形态学方法,适合小目标增强
  • 最大中值滤波:对脉冲噪声鲁棒
  • 局部对比度方法(LCM):基于人眼视觉特性
  • 改进的LCM:增强的对比度计算
  • 梯度加权方法:结合梯度信息

3. 使用方法

  1. 将程序保存为infrared_target_detection.m
  2. 在MATLAB中运行
  3. 程序会:
    • 生成模拟红外图像(或使用您的真实图像)
    • 应用各种检测算法
    • 显示比较结果
    • 评估检测性能

参考代码 matlab 编写 红外弱小目标检测 www.youwenfan.com/contentali/113027.html

4. 使用真实数据

要使用您自己的红外图像:

% 替换第13行的 img = generateSimulatedIRImage();
% 改为:
img = imread('your_image.pgm');  % 或您的图像格式
img = rgb2gray(img);  % 如果是彩色图,转为灰度

5. 参数调整建议

  • 目标大小:调整结构元素大小(第148行)
  • 检测灵敏度:调整阈值参数(第248行)
  • 窗口大小:根据目标大小调整(第161、179行)
相关文章
|
21小时前
|
人工智能 自然语言处理 文字识别
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
Qwen3.7-Max是阿里云百炼面向智能体时代推出的新一代旗舰模型,对标GPT-5.5、Claude Opus 4.7等闭源旗舰。该模型支持百万级token上下文窗口,具备顶级推理能力、多模态搜索与视觉理解增强、流式输出低延迟响应等核心优势,覆盖编程、办公、长周期自主执行等复杂场景。同时支持OpenAI接口兼容,便于系统快速迁移。用户可通过Token Plan团队或节省计划等订阅方式灵活调用,适合企业级高要求场景使用。
7507 32
阿里云百炼Qwen3.7-Max简介:能力、优势、支持订阅计划参考
|
21小时前
|
数据采集 人工智能 前端开发
让 Coding Agent 从黑盒到透明:阿里云 Agent 观测审计数据采集实践
AI Agent 规模化落地带来执行黑盒、行为难追溯、成本难度量三大难题。阿里云基于 OTel 标准,面向 Coding Agent、个人通用助理和框架型 Agent,推出 LoongSuite Pilot、插件及探针等无侵入采集方案,让 Agent 实现可看见、可分析、可审计、可治理。
643 142
|
21小时前
|
人工智能 缓存 自然语言处理
阿里Qwen3.7-Max评测:Agent能力显著提升,耗时与调用成本大幅下降
阿里云百炼推出面向智能体的旗舰大模型Qwen3.7-Max,具备长周期自主执行能力,显著提升编程、办公自动化等复杂任务处理水平;支持MCP集成与多框架兼容,并以限时5折+100万Tokens免费试用大幅降低使用门槛,助力企业高效落地AI应用。在阿里云百炼平台快速体验:https://t.aliyun.com/U/fPVHqY
|
21小时前
|
人工智能 安全 定位技术
CodeGraph深度解析 让Claude Code工具调用直降七成的核心原理与实操教程
如今以Claude Code为代表的AI编程智能体已经成为开发者日常编码、项目重构、漏洞修复的必备工具。但在长期使用过程中,几乎所有开发者都会遇到同一个明显痛点:AI虽然具备强大的代码生成与分析能力,却常常陷入盲目探索的循环中。
1262 2
|
21小时前
|
人工智能 弹性计算 运维
阿里云发布堡垒机智能运维Agent,运维交互进入自然语言新时代
支持自然语言运维,提升效率与安全双保障。
1168 1
|
21小时前
|
存储 定位技术 数据库
CodeGraph 如何让 Claude Code减少 7 成工具调用?
CodeGraph 为 Coding Agent 提供本地代码知识图谱,把函数、类、调用链和框架路由提前整理成“项目地图”,减少盲目搜索和文件读取。它不是新 Agent,而是上下文基础设施,让 Agent 更快找到正确代码路径,平均减少 7 成工具调用。
1316 4
|
21小时前
|
人工智能 运维 JavaScript
阿里云Qoder CN(原通义灵码)全解析 产品形态、版本划分与技术适配说明
在AI辅助开发与智能办公工具持续普及的当下,阿里云旗下原通义灵码正式更名为Qoder CN,同时延伸出QoderWork CN、Qoder CN CLI、Qoder CN Mobile等多款配套产品,形成覆盖代码开发、日常办公、终端交互、移动端使用的完整工具矩阵。Qoder CN核心定位为AI智能编码助手,深度适配主流代码编辑器、集成开发环境以及终端场景;QoderWork CN则偏向桌面端综合办公辅助,二者面向不同使用场景,划分了多个版本档位,搭配差异化资源配额、功能权限与计费规则,同时兼容多款主流大模型。
395 4
|
21小时前
|
JavaScript 定位技术 API
CodeGraph 爆火:编程 Agent 需要的不是更多上下文,而是一张提前画好的代码地图
CodeGraph 是一款爆火的本地代码智能工具,通过 tree-sitter 解析 AST 构建结构化知识图谱(存于 SQLite),为编程 Agent 提前生成“代码地图”。它显著降低 Agent 在中大型项目中的探索成本——实测工具调用减少71%、Token 降57%、速度提升46%,支持19+语言及主流框架路由识别,完全离线、无需 API Key。
344 1
CodeGraph 爆火:编程 Agent 需要的不是更多上下文,而是一张提前画好的代码地图
|
21小时前
|
存储 安全 Java
AgentScope Java 2.0:打造分布式、企业级智能体底座
AgentScope 2.0 面向分布式部署、稳定运行、权限安全等企业级需求全面升级,打造支持多租户隔离与长期稳定运行的企业级智能体底座。
|
21小时前
|
人工智能 运维 API
2026年阿里云百炼通义千问Qwen3.7-plus深度介绍 功能特性、使用优势及618大促订阅方案指南
大模型技术的普及,让AI能力逐步融入个人办公、内容创作、代码编写、企业运营、教育培训等各类场景。不同定位的模型对应不同使用需求,旗舰级模型性能强劲但使用成本偏高,轻量化模型价格低廉却难以胜任复杂任务,而介于两者之间的中端主力模型,凭借均衡的能力、亲民的定价、广泛的场景适配性,成为绝大多数个人用户、小型团队、中小企业的首选。
462 1