基于运动补偿的前景检测算法

这段代码实现了基于运动补偿的前景检测算法。

主要功能包括:

  • 运动补偿模块:使用基于网格的 KLT 特征跟踪算法计算两帧之间的运动,然后通过单应性变换实现帧间运动补偿。
  • 前景检测模块:结合两帧运动补偿结果,通过帧间差分计算前景掩码。
  • 异常处理:添加了图像加载检查和异常捕获,提高了代码的健壮性。
  • 路径处理:自动创建保存目录,避免因目录不存在导致的错误。

使用时需要提供三帧连续图像:两个参考帧和当前帧。代码会计算出前景掩码并保存为图像文件。

import cv2
import numpy as np
import os
import sysdef motion_compensate(frame1, frame2):"""使用基于网格的KLT特征跟踪实现两帧之间的运动补偿参数:frame1: 前一帧图像(BGR格式)frame2: 当前帧图像(BGR格式)返回:compensated: 运动补偿后的图像mask: 补偿区域的掩码avg_dst: 平均运动距离motion_x: x方向平均运动量motion_y: y方向平均运动量homography_matrix: 单应性变换矩阵"""# 设置LK光流参数lk_params = dict(winSize=(15, 15), maxLevel=3,criteria=(cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 30, 0.003))# 图像预处理和网格点生成width = frame2.shape[1]height = frame2.shape[0]scale = 2  # 放大图像以获得更精确的跟踪# 调整图像大小以提高特征点检测精度frame1_grid = cv2.resize(frame1, (960 * scale, 540 * scale), dst=None, interpolation=cv2.INTER_CUBIC)frame2_grid = cv2.resize(frame2, (960 * scale, 540 * scale), dst=None, interpolation=cv2.INTER_CUBIC)width_grid = frame2_grid.shape[1]height_grid = frame2_grid.shape[0]gridSizeW = 32 * 2  # 网格宽度gridSizeH = 24 * 2  # 网格高度# 生成网格点作为特征点p1 = []grid_numW = int(width_grid / gridSizeW - 1)grid_numH = int(height_grid / gridSizeH - 1)for i in range(grid_numW):for j in range(grid_numH):# 将点放置在每个网格中心point = (np.float32(i * gridSizeW + gridSizeW / 2.0), np.float32(j * gridSizeH + gridSizeH / 2.0))p1.append(point)p1 = np.array(p1)pts_num = grid_numW * grid_numHpts_prev = p1.reshape(pts_num, 1, 2)# 计算光流pts_cur, st, err = cv2.calcOpticalFlowPyrLK(frame1_grid, frame2_grid, pts_prev, None, **lk_params)# 选择跟踪成功的点good_new = pts_cur[st == 1]  # 当前帧中的跟踪点good_old = pts_prev[st == 1]  # 前一帧中的跟踪点# 计算运动距离和位移motion_distance = []translate_x = []translate_y = []for i, (new, old) in enumerate(zip(good_new, good_old)):a, b = new.ravel()c, d = old.ravel()motion_distance0 = np.sqrt((a - c) * (a - c) + (b - d) * (b - d))# 过滤异常大的运动值if motion_distance0 > 50:continuetranslate_x0 = a - ctranslate_y0 = b - dmotion_distance.append(motion_distance0)translate_x.append(translate_x0)translate_y.append(translate_y0)motion_dist = np.array(motion_distance)motion_x = np.mean(np.array(translate_x)) if translate_x else 0motion_y = np.mean(np.array(translate_y)) if translate_y else 0avg_dst = np.mean(motion_dist) if motion_dist.size > 0 else 0# 计算单应性变换矩阵if len(good_old) < 15:# 点太少时使用近似恒等变换homography_matrix = np.array([[0.999, 0, 0], [0, 0.999, 0], [0, 0, 1]])else:# 使用RANSAC算法估计单应性矩阵homography_matrix, status = cv2.findHomography(good_new, good_old, cv2.RANSAC, 3.0)# 应用单应性变换进行运动补偿compensated = cv2.warpPerspective(frame1, homography_matrix, (width, height), flags=cv2.INTER_LINEAR + cv2.WARP_INVERSE_MAP)# 生成掩码以指示变换区域vertex = np.array([[0, 0], [width, 0], [width, height], [0, height]], dtype=np.float32).reshape(-1, 1, 2)homo_inv = np.linalg.inv(homography_matrix)vertex_trans = cv2.perspectiveTransform(vertex, homo_inv)vertex_transformed = np.array(vertex_trans, dtype=np.int32).reshape(1, 4, 2)im = np.zeros(frame1.shape[:2], dtype='uint8')cv2.polylines(im, vertex_transformed, 1, 255)cv2.fillPoly(im, vertex_transformed, 255)mask = 255 - imreturn compensated, mask, avg_dst, motion_x, motion_y, homography_matrixdef FD_mask(lastFrame1, lastFrame2, currentFrame, save_path='data/mask.jpg'):"""使用两帧运动补偿计算前景掩码参数:lastFrame1: 第一参考帧(BGR格式)lastFrame2: 第二参考帧(BGR格式)currentFrame: 当前帧(BGR格式)save_path: 结果掩码保存路径"""# 图像预处理:高斯模糊和灰度转换lastFrame1 = cv2.GaussianBlur(lastFrame1, (11, 11), 0)lastFrame1 = cv2.cvtColor(lastFrame1, cv2.COLOR_BGR2GRAY)lastFrame2 = cv2.GaussianBlur(lastFrame2, (11, 11), 0)lastFrame2 = cv2.cvtColor(lastFrame2, cv2.COLOR_BGR2GRAY)currentFrame = cv2.GaussianBlur(currentFrame, (11, 11), 0)currentFrame = cv2.cvtColor(currentFrame, cv2.COLOR_BGR2GRAY)# 计算第一参考帧到第二参考帧的运动补偿img_compensate1, mask1, avg_dist1, motion_x1, motion_y1, homo_matrix = motion_compensate(lastFrame1, lastFrame2)frameDiff1 = cv2.absdiff(lastFrame2, img_compensate1)# 计算当前帧到第二参考帧的运动补偿img_compensate2, mask2, avg_dist2, motion_x2, motion_y2, homo_matrix2 = motion_compensate(currentFrame, lastFrame2)frameDiff2 = cv2.absdiff(lastFrame2, img_compensate2)# 融合两个差分结果frameDiff = (frameDiff1 + frameDiff2) / 2# 保存结果os.makedirs(os.path.dirname(save_path), exist_ok=True)cv2.imwrite(save_path, frameDiff)print(f'前景掩码已保存至: {save_path}')return frameDiffif __name__ == "__main__":# 示例:加载三帧图像并计算前景掩码# 请确保这些图像存在,或者修改为您自己的图像路径try:lastFrame1 = cv2.imread('data/Test_images/images/phantom05_0600.jpg')lastFrame3 = cv2.imread('data/Test_images/images/phantom05_0602.jpg')currentFrame = cv2.imread('data/Test_images/images/phantom05_0604.jpg')if lastFrame1 is None or lastFrame3 is None or currentFrame is None:print("错误: 无法加载图像,请检查文件路径!")else:FD_mask(lastFrame1, lastFrame3, currentFrame)except Exception as e:print(f"程序执行出错: {e}")    
#include <opencv2/opencv.hpp>
#include <vector>
#include <iostream>
#include <numeric>
#include <cmath>using namespace cv;
using namespace std;struct MotionCompensationResult {Mat compensated;Mat mask;float avg_dst;float motion_x;float motion_y;Mat homography_matrix;
};MotionCompensationResult motion_compensate(const Mat& frame1, const Mat& frame2) {// KLT 跟踪参数TermCriteria term_criteria(TermCriteria::EPS | TermCriteria::COUNT, 30, 0.003);Size win_size(15, 15);int max_level = 3;// 图像缩放int scale = 2;Mat frame1_grid, frame2_grid;resize(frame1, frame1_grid, Size(960 * scale, 540 * scale), 0, 0, INTER_CUBIC);resize(frame2, frame2_grid, Size(960 * scale, 540 * scale), 0, 0, INTER_CUBIC);// 创建网格点int gridSizeW = 32 * 2;int gridSizeH = 24 * 2;int grid_numW = static_cast<int>(frame2_grid.cols / gridSizeW - 1);int grid_numH = static_cast<int>(frame2_grid.rows / gridSizeH - 1);vector<Point2f> p1;for (int i = 0; i < grid_numW; i++) {for (int j = 0; j < grid_numH; j++) {p1.push_back(Point2f(i * gridSizeW + gridSizeW / 2.0f, j * gridSizeH + gridSizeH / 2.0f));}}int pts_num = grid_numW * grid_numH;Mat pts_prev = Mat(p1).reshape(2, pts_num);// 计算光流vector<Point2f> pts_cur;vector<uchar> status;vector<float> err;calcOpticalFlowPyrLK(frame1_grid, frame2_grid, pts_prev, pts_cur, status, err, win_size, max_level, term_criteria);// 筛选好点vector<Point2f> good_new, good_old;for (size_t i = 0; i < status.size(); i++) {if (status[i]) {good_new.push_back(pts_cur[i]);good_old.push_back(p1[i]);}}// 计算运动距离和位移vector<float> motion_distance;vector<float> translate_x, translate_y;for (size_t i = 0; i < good_new.size(); i++) {float dx = good_new[i].x - good_old[i].x;float dy = good_new[i].y - good_old[i].y;float dist = sqrt(dx * dx + dy * dy);if (dist > 50) continue;motion_distance.push_back(dist);translate_x.push_back(dx);translate_y.push_back(dy);}// 计算平均值float avg_dst = 0, motion_x = 0, motion_y = 0;if (!motion_distance.empty()) {avg_dst = accumulate(motion_distance.begin(), motion_distance.end(), 0.0f) / motion_distance.size();}if (!translate_x.empty()) {motion_x = accumulate(translate_x.begin(), translate_x.end(), 0.0f) / translate_x.size();motion_y = accumulate(translate_y.begin(), translate_y.end(), 0.0f) / translate_y.size();}// 计算单应性矩阵Mat homography_matrix;if (good_old.size() < 15) {homography_matrix = (Mat_<double>(3, 3) << 0.999, 0, 0, 0, 0.999, 0, 0, 0, 1);} else {homography_matrix = findHomography(good_new, good_old, RANSAC, 3.0);}// 运动补偿Mat compensated;warpPerspective(frame1, compensated, homography_matrix, Size(frame1.cols, frame1.rows), INTER_LINEAR + WARP_INVERSE_MAP);// 计算掩膜vector<Point2f> vertex;vertex.push_back(Point2f(0, 0));vertex.push_back(Point2f(frame1.cols, 0));vertex.push_back(Point2f(frame1.cols, frame1.rows));vertex.push_back(Point2f(0, frame1.rows));Mat vertex_mat = Mat(vertex).reshape(2);Mat homo_inv = homography_matrix.inv();vector<Point2f> vertex_trans;perspectiveTransform(vertex_mat, vertex_trans, homo_inv);vector<Point> vertex_transformed;for (const auto& pt : vertex_trans) {vertex_transformed.push_back(Point(static_cast<int>(pt.x), static_cast<int>(pt.y)));}Mat mask = Mat::zeros(frame1.size(), CV_8UC1);vector<vector<Point>> contours;contours.push_back(vertex_transformed);polylines(mask, contours, true, Scalar(255), 1);fillPoly(mask, contours, Scalar(255));mask = 255 - mask;return {compensated, mask, avg_dst, motion_x, motion_y, homography_matrix};
}void FD_mask(const Mat& lastFrame1, const Mat& lastFrame2, const Mat& currentFrame, const string& save_path = "mask.jpg") {// 图像预处理Mat lastFrame1_gray, lastFrame2_gray, currentFrame_gray;GaussianBlur(lastFrame1, lastFrame1_gray, Size(11, 11), 0);GaussianBlur(lastFrame2, lastFrame2_gray, Size(11, 11), 0);GaussianBlur(currentFrame, currentFrame_gray, Size(11, 11), 0);cvtColor(lastFrame1_gray, lastFrame1_gray, COLOR_BGR2GRAY);cvtColor(lastFrame2_gray, lastFrame2_gray, COLOR_BGR2GRAY);cvtColor(currentFrame_gray, currentFrame_gray, COLOR_BGR2GRAY);// 第一组运动补偿auto result1 = motion_compensate(lastFrame1_gray, lastFrame2_gray);Mat frameDiff1;absdiff(lastFrame2_gray, result1.compensated, frameDiff1);// 第二组运动补偿auto result2 = motion_compensate(currentFrame_gray, lastFrame2_gray);Mat frameDiff2;absdiff(lastFrame2_gray, result2.compensated, frameDiff2);// 计算最终差分Mat frameDiff;frameDiff1.convertTo(frameDiff1, CV_32F);frameDiff2.convertTo(frameDiff2, CV_32F);frameDiff = (frameDiff1 + frameDiff2) / 2;frameDiff.convertTo(frameDiff, CV_8U);// 保存结果imwrite(save_path, frameDiff);cout << "done!" << endl;
}int main() {// 读取图像Mat lastFrame1 = imread("data/Test_images/images/phantom05_0600.jpg");Mat lastFrame3 = imread("data/Test_images/images/phantom05_0602.jpg");Mat currentFrame = imread("data/Test_images/images/phantom05_0604.jpg");/*Mat lastFrame1 = imread("250514_430.bmp");Mat lastFrame3 = imread("250514_463.bmp");Mat currentFrame = imread("250514_490.bmp");*/// 检查图像是否成功加载if (lastFrame1.empty() || lastFrame3.empty() || currentFrame.empty()) {cout << "无法加载图像!" << endl;return -1;}// 执行帧间差分FD_mask(lastFrame1, lastFrame3, currentFrame);return 0;
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/905530.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

使用matlab进行数据拟合

目录 一、工作区建立数据 二、曲线拟合器(在"APP"中) 三、曲线拟合函数及参数 四、 在matlab中编写代码 一、工作区建立数据 首先&#xff0c;将数据在matlab工作区中生成。如图1所示&#xff1a; 图 1 二、曲线拟合器(在"APP"中) 然后&#xff0c;…

Playwright 安装配置文件详解

Playwright 安装&配置文件详解 环境准备 Node.js 14.0&#xff08;推荐 LTS 版本&#xff09;npm&#xff08;推荐使用最新版&#xff09;支持 Windows、macOS、Linux 一步到位的官方推荐安装方式 1. 进入你的项目目录 # Windows cd 路径\到\你的项目 # macOS/Linux cd…

中国古代史4

东汉 公元25年&#xff0c;刘秀建立东汉&#xff0c;定都洛阳&#xff0c;史称光武中兴 白马寺&#xff1a;汉明帝时期建立&#xff0c;是佛教传入中国后兴建的第一座官办寺院&#xff0c;有中国佛教的“祖庭”和“释源”之称&#xff0c;距今1900多年历史 班超—西域都护—投…

springboot + mysql8降低版本到 mysql5.7

springboot mysql8降低版本到 mysql5.7 <dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.49</version></dependency>spring:datasource:driverClassName: com.mysql.jdbc.D…

4.4java常用类

在 Java 中&#xff0c;System 和 Runtime 类都是 java.lang 包下非常重要的类&#xff0c;它们提供了与系统交互以及管理 Java 虚拟机&#xff08;JVM&#xff09;运行时环境的功能。 System 类 System 类包含了一些有用的类字段和方法&#xff0c;它不能被实例化&#xff0…

【嵌入式笔记】Modbus TCP

1.概述 定义&#xff1a;Modbus TCP 是 Modbus 协议的变体&#xff0c;基于 TCP/IP 协议栈&#xff0c;用于通过以太网实现工业设备间的通信。 背景&#xff1a;由施耐德电气&#xff08;原 Modicon 公司&#xff09;在 1999 年发布&#xff0c;将传统的 Modbus RTU/ASCII 适配…

《解锁React Native与Flutter:社交应用启动速度优化秘籍》

React Native和Flutter作为当下热门的跨平台开发框架&#xff0c;在优化应用启动性能方面各有千秋。今天&#xff0c;我们就深入剖析它们独特的策略与方法。 React Native应用的初始包大小对启动速度影响显著。在打包阶段&#xff0c;通过精准分析依赖&#xff0c;去除未使用的…

R语言学习--Day02--实战经验反馈

最近在做需要用R语言做数据清洗的项目&#xff0c;在网上看再多的技巧与语法&#xff0c;都不如在项目中实战学习的快&#xff0c;下面是我通过实战得来的经验。 判断Rstudio是否卡死 很多时候&#xff0c;我们在运行R语言代码时&#xff0c;即使只是运行框选的几行代码&#…

How Sam‘s Club nudge customers into buying more

Here’s how Sam’s Club (or similar warehouse memberships) nudge customers into buying more: It’s a classic psychological strategy rooted in sunk cost fallacy and loss aversion. 1. Prepaid Membership Creates a “Sunk Cost” Once you’ve paid the annual …

OpenHarmony系统HDF驱动开发介绍(补充)

一、HDF驱动简介 HDF&#xff08;Hardware Driver Foundation&#xff09;驱动框架&#xff0c;为驱动开发者提供驱动框架能力&#xff0c;包括驱动加载、驱动服务管理、驱动消息机制和配置管理。 简单来说&#xff1a;HDF框架的驱动和Linux的驱动比较相似都是由配置文件和驱动…

自然语言处理 (NLP) 入门:NLTK 与 SpaCy 的初体验

自然语言处理入门&#xff1a;NLTK 与 SpaCy 的初体验 在当今数字化飞速发展的浪潮中&#xff0c;自然语言处理&#xff08;NLP&#xff09;已经成为了极具热度的技术领域。自然语言处理的核心目标是让计算机能够理解、分析并生成人类语言&#xff0c;其应用场景极为广泛&…

LLaVA:开源多模态大语言模型深度解析

一、基本介绍 1.1 项目背景与定位 LLaVA(Large Language and Vision Assistant)是由Haotian Liu等人开发的开源多模态大语言模型,旨在实现GPT-4级别的视觉-语言交互能力。该项目通过视觉指令微调技术,将预训练的视觉编码器与语言模型深度融合,在多个多模态基准测试中达到…

如何利用大模型对文章进行分段,提高向量搜索的准确性?

利用大模型对文章进行分段以提高向量搜索准确性,需结合文本语义理解、分块策略优化以及向量表示技术。以下是系统性的解决方案: 一、分块策略的核心原则 语义完整性优先 分块需确保每个文本单元在语义上独立且完整。研究表明,当分块内容保持单一主题时,向量嵌入的语义表征能…

Java高频面试之并发编程-17

volatile 和 synchronized 的区别 在 Java 并发编程中&#xff0c;volatile 和 synchronized 是两种常用的同步机制&#xff0c;但它们的适用场景和底层原理有显著差异。以下是两者的详细对比&#xff1a; 1. 核心功能对比 特性volatilesynchronized原子性不保证复合操作的原…

技术债务积累,如何进行有效管理

识别和评估技术债务、明确技术债务的优先级、制定系统的还债计划、持续监控与预防技术债务产生是有效管理技术债务积累的重要策略。其中尤其要注重识别和评估技术债务&#xff0c;只有准确识别技术债务的种类和严重程度&#xff0c;才能制定出高效且有针对性的解决方案&#xf…

安装windows版本的nacos

一、下载nacos安装包 浏览器搜索nacos&#xff0c;进入nacos官网 https://nacos.io/docs/latest/overview/ 选择下载windows版本的nacos 二、解压缩 三、进入bin目录&#xff0c;cmd命令行窗口 四、启动nacos 查看日志 五、打开可视化页面查看 以上&#xff0c;就是安装wind…

小结:Android系统架构

https://developer.android.com/topic/architecture?hlzh-cn Android系统的架构&#xff0c;分为四个主要层次&#xff1a;应用程序层、应用框架层、库和运行时层以及Linux内核层。&#xff1a; 1. 应用程序层&#xff08;Applications&#xff09; 功能&#xff1a;这一层包…

鸿蒙5.0项目开发——鸿蒙天气项目的实现(欢迎页)

【高心星出品】 文章目录 欢迎页面效果数据字典创建数据库表格Splash页面页面功能欢迎页代码亮点 项目按照从数据库连接层–视图层–业务逻辑层这种三层架构开发&#xff0c;所以先设计了数据库表格的结构&#xff0c;在EntryAbility中创建表格。 欢迎页面效果 数据字典 sear…

使用谱聚类将相似度矩阵分为2类

使用谱聚类将相似度矩阵分为2类的步骤如下&#xff1a; 构建相似度矩阵&#xff1a;提供的1717矩阵已满足对称性且对角线为1。 计算度矩阵&#xff1a;对每一行求和得到各节点的度&#xff0c;形成对角矩阵。 计算归一化拉普拉斯矩阵&#xff1a;采用对称归一化形式 LsymI−D…

MySQL 8.0 OCP 英文题库解析(三)

Oracle 为庆祝 MySQL 30 周年&#xff0c;截止到 2025.07.31 之前。所有人均可以免费考取原价245美元的MySQL OCP 认证。 从今天开始&#xff0c;将英文题库免费公布出来&#xff0c;并进行解析&#xff0c;帮助大家在一个月之内轻松通过OCP认证。 本期公布试题16~25 试题16:…