利用python装饰器,客制化图像处理功能

文章目录

有时间再写

detection_plugin.py

python 复制代码
# detection_plugin.py
import cv2
import numpy as np
from plugin_interface import ImageProcessingPlugin

class EdgeDetectionPlugin(ImageProcessingPlugin):
    def process_image(self, image_path):
        # 读取图像
        image = cv2.imread(image_path, cv2.IMREAD_COLOR)
        if image is None:
            return None, "Image not found"

        # 转换为灰度图像
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

        # 边缘检测
        edges = cv2.Canny(gray, 100, 200)

        return edges, None

main.py

python 复制代码
import sys
import importlib.util
from PyQt5.QtWidgets import QApplication, QMainWindow, QFileDialog, QPushButton, QLabel, QVBoxLayout, QWidget, QMessageBox
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
from plugin_interface import ImageProcessingPlugin

class ImageViewer(QWidget):
    def __init__(self):
        super().__init__()
        self.image_label = QLabel()
        layout = QVBoxLayout()
        layout.addWidget(self.image_label)
        self.setLayout(layout)

    def load_image(self, pixmap):
        self.image_label.setPixmap(pixmap)

    def load_image_from_path(self, file_path):
        pixmap = QPixmap(file_path)
        self.load_image(pixmap)

    def display_edges(self, edges):
        # 转换边缘检测结果为 QPixmap 显示
        height, width = edges.shape
        qimage = QImage(edges.data, width, height, width, QImage.Format_Grayscale8)
        pixmap = QPixmap.fromImage(qimage)
        self.load_image(pixmap)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('Image Viewer with Plugin')
        self.setGeometry(100, 100, 800, 600)

        self.current_plugin = None
        self.file_path = None
        self.plugin_path = None

        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)

        # 图像查看器
        self.image_viewer = ImageViewer()
        layout.addWidget(self.image_viewer)

        # 加载图像按钮
        self.load_button = QPushButton('Load Image')
        self.load_button.clicked.connect(self.load_image)
        layout.addWidget(self.load_button)

        # 执行检测按钮
        self.detect_button = QPushButton('Detect Edges')
        self.detect_button.clicked.connect(self.detect_edges)
        layout.addWidget(self.detect_button)

        # 状态标签
        self.status_label = QLabel('Status: ')
        layout.addWidget(self.status_label)

        # 选择插件按钮
        self.load_plugin_button = QPushButton('Load Plugin')
        self.load_plugin_button.clicked.connect(self.load_plugin)
        layout.addWidget(self.load_plugin_button)

    def load_image(self):
        self.file_path, _ = QFileDialog.getOpenFileName(self, 'Open Image File', '', 'Images (*.png *.xpm *.jpg *.bmp)')
        if self.file_path:
            self.image_viewer.load_image_from_path(self.file_path)
            self.status_label.setText(f'Status: Loaded {self.file_path}')

    def load_plugin(self):
        # 选择插件文件
        self.plugin_path, _ = QFileDialog.getOpenFileName(self, 'Select Plugin File', '', 'Python Files (*.py)')
        if self.plugin_path:
            try:
                # 动态加载插件
                spec = importlib.util.spec_from_file_location("plugin", self.plugin_path)
                plugin_module = importlib.util.module_from_spec(spec)
                spec.loader.exec_module(plugin_module)

                # 假设插件文件中有一个名为 EdgeDetectionPlugin 的类
                plugin_class = getattr(plugin_module, 'EdgeDetectionPlugin', None)
                if plugin_class and issubclass(plugin_class, ImageProcessingPlugin):
                    self.current_plugin = plugin_class()
                    QMessageBox.information(self, 'Plugin Loaded', 'Plugin loaded successfully.')
                else:
                    QMessageBox.warning(self, 'Plugin Error', 'The selected file does not contain a valid ImageProcessingPlugin implementation.')
            except Exception as e:
                QMessageBox.warning(self, 'Plugin Error', f'Failed to load plugin: {e}')

    def detect_edges(self):
        if not self.file_path:
            QMessageBox.warning(self, 'No Image Loaded', 'Please load an image first.')
            return

        if not self.current_plugin:
            QMessageBox.warning(self, 'No Plugin Loaded', 'Please load a plugin first.')
            return

        edges, error = self.current_plugin.process_image(self.file_path)
        if error:
            QMessageBox.warning(self, 'Detection Error', error)
            return

        self.image_viewer.display_edges(edges)
        self.status_label.setText(f'Status: Edges Detected')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main_window = MainWindow()
    main_window.show()
    sys.exit(app.exec_())

plugin_interface.py

python 复制代码
from abc import ABC, abstractmethod

class ImageProcessingPlugin(ABC):
    @abstractmethod
    def process_image(self, image_path):
        """处理图像并返回结果"""
        pass
相关推荐
bryant_meng2 小时前
【python】OpenCV—Image Moments
开发语言·python·opencv·moments·图片矩
KevinRay_2 小时前
Python超能力:高级技巧让你的代码飞起来
网络·人工智能·python·lambda表达式·列表推导式·python高级技巧
Captain823Jack3 小时前
nlp新词发现——浅析 TF·IDF
人工智能·python·深度学习·神经网络·算法·自然语言处理
资源补给站3 小时前
大恒相机开发(2)—Python软触发调用采集图像
开发语言·python·数码相机
Captain823Jack4 小时前
w04_nlp大模型训练·中文分词
人工智能·python·深度学习·神经网络·算法·自然语言处理·中文分词
PieroPc4 小时前
Python 自动化 打开网站 填表登陆 例子
运维·python·自动化
VinciYan5 小时前
基于Jenkins+Docker的自动化部署实践——整合Git与Python脚本实现远程部署
python·ubuntu·docker·自动化·jenkins·.net·运维开发
测试老哥5 小时前
外包干了两年,技术退步明显。。。。
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
終不似少年遊*5 小时前
美国加州房价数据分析01
人工智能·python·机器学习·数据挖掘·数据分析·回归算法
如若1235 小时前
对文件内的文件名生成目录,方便查阅
java·前端·python