
在物理实验实时监测等场景中,摄像头以固定频率(例如2.5hz)采集图像,并需要对这些图像进行即时处理和可视化。然而,当程序从静态数据源切换到动态、实时添加图像的文件夹时,常会遇到性能下降、数据异常甚至错误的结果。这通常是由于代码效率不足、数据同步问题以及不当的实时文件i/o操作所导致。本教程将深入探讨如何优化这类实时图像处理系统,提升其性能和稳定性。
原始代码中存在大量全局变量,导致程序状态管理混乱,可读性和可维护性极差。此外,UI更新逻辑与数据处理逻辑混杂,进一步增加了复杂性。通过引入面向对象设计,可以有效解决这些问题。
全局变量虽然使用方便,但在复杂系统中会导致以下问题:
将相关的变量(如center、radius、拖拽状态等)和操作(如绘图、图像变换、鼠标事件处理)封装到一个类中,可以清晰地管理程序状态。
import numpy as np
import cv2
import pyqtgraph as pg
from pyqtgraph.Qt import QtCore, QtWidgets
class ImageProcessor:
def __init__(self, initial_image_path=None):
# 初始化图像处理器的状态
self.center = (0, 0)
self.radius = 0
self.is_dragging_center = False
self.is_dragging_radius = False
self.resized_image = None
self.original_image_shape = (0, 0) # 用于缩放ROI坐标
# PyqtGraph 相关
self.brightness_history = []
self.std_history = []
self.pw = pg.PlotWidget(title='Mean Brightness vs Image Round')
self.pw.setLabel('left', 'Mean Brightness')
self.pw.setLabel('bottom', 'Image Round')
self.scatter = pg.ScatterPlotItem(size=10, pen=pg.mkPen(None), brush=pg.mkBrush(255, 0, 0, 120))
self.line = pg.PlotDataItem(pen=pg.mkPen(color=(0,0,255), width=2))
self.pw.addItem(self.line)
self.pw.addItem(self.scatter)
if initial_image_path:
self.load_and_prepare_initial_image(initial_image_path)
def load_and_prepare_initial_image(self, image_path, scale_percent=60):
# 加载初始图像用于ROI选择
image = cv2.imread(image_path)
if image is None:
print(f"Error: Could not load image from {image_path}")
return
self.original_image_shape = image.shape
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
colored_image = cv2.applyColorMap(gray_img, cv2.COLORMAP_PINK)
width = int(image.shape[1] * scale_percent / 100)
height = int(image.shape[0] * scale_percent / 100)
self.resized_image = cv2.resize(colored_image, (width, height), interpolation=cv2.INTER_AREA)
# 初始ROI位置
self.center = (self.resized_image.shape[1] // 2, self.resized_image.shape[0] // 2)
self.radius = min(self.resized_image.shape[1] // 3, self.resized_image.shape[0] // 3)
def draw_roi_on_image(self, img):
# 在图像上绘制ROI圆
display_image = img.copy()
cv2.circle(display_image, self.center, self.radius, (0, 255, 0), 2)
cv2.circle(display_image, self.center, 5, (0, 0, 255), thickness=cv2.FILLED)
return display_image
def on_mouse(self, event, x, y, flags, param):
# 鼠标事件回调,用于调整ROI
if event == cv2.EVENT_LBUTTONDOWN:
if np.sqrt((x -以上就是实时图像数据采集与分析:Python性能优化与并发处理实践的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号