利用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
相关推荐
刽子手发艺32 分钟前
Selenium+OpenCV处理滑块验证问题
opencv·selenium·webpack
bst@微胖子36 分钟前
Python高级语法之selenium
开发语言·python·selenium
查理零世2 小时前
【蓝桥杯集训·每日一题2025】 AcWing 6118. 蛋糕游戏 python
python·算法·蓝桥杯
魔尔助理顾问3 小时前
一个简洁高效的Flask用户管理示例
后端·python·flask
java1234_小锋3 小时前
一周学会Flask3 Python Web开发-request请求对象与url传参
开发语言·python·flask·flask3
诚信爱国敬业友善6 小时前
常见排序方法的总结归类
开发语言·python·算法
架构默片7 小时前
【JAVA工程师从0开始学AI】,第五步:Python类的“七十二变“——当Java的铠甲遇见Python的液态金属
java·开发语言·python
小哥山水之间8 小时前
在 Python 中操作 Excel 文件
开发语言·python·excel
AomanHao9 小时前
图像质量评价指标-UCIQE-UIQM
图像处理·人工智能·计算机视觉·评价指标
wang_yb10 小时前
『Python底层原理』--CPython的变量实现机制
python·databook