利用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
相关推荐
努力的家伙是不讨厌的10 分钟前
解析json导出csv或者直接入库
开发语言·python·json
云空32 分钟前
《Python 与 SQLite:强大的数据库组合》
数据库·python·sqlite
凤枭香1 小时前
Python OpenCV 傅里叶变换
开发语言·图像处理·python·opencv
测试杂货铺1 小时前
外包干了2年,快要废了。。
自动化测试·软件测试·python·功能测试·测试工具·面试·职场和发展
艾派森1 小时前
大数据分析案例-基于随机森林算法的智能手机价格预测模型
人工智能·python·随机森林·机器学习·数据挖掘
小码的头发丝、2 小时前
Django中ListView 和 DetailView类的区别
数据库·python·django
ctrey_2 小时前
2024-11-4 学习人工智能的Day21 openCV(3)
人工智能·opencv·学习
Chef_Chen3 小时前
从0开始机器学习--Day17--神经网络反向传播作业
python·神经网络·机器学习
千澜空3 小时前
celery在django项目中实现并发任务和定时任务
python·django·celery·定时任务·异步任务
可均可可3 小时前
C++之OpenCV入门到提高004:Mat 对象的使用
c++·opencv·mat·imread·imwrite