利用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
相关推荐
fmc1211043 分钟前
Excel文档的读取(3)
java·前端·python
极客小张7 分钟前
基于OpenCV与MQTT的停车场车牌识别系统:结合SQLite和Flask的设计流程
arm开发·人工智能·单片机·opencv·物联网·flask·毕业设计
转瞬都有24 分钟前
sqli-labs靶场自动化利用工具——第10关
python·sql·网络安全·自动化
z千鑫27 分钟前
【数据分析】利用Python+AI+工作流实现自动化数据分析-全流程讲解
人工智能·python·ai·数据分析·自动化·ai编程·ai工作流
AI让世界更懂你33 分钟前
漫谈设计模式 [13]:命令模式
python·设计模式·命令模式
Solidao40 分钟前
从0开始的算法(数据结构和算法)基础(十一)
数据结构·python·算法
山水阳泉曲1 小时前
opencv将灰度图转为彩色图片
图像处理·opencv·计算机视觉
低调求绕过,没事写博客1 小时前
二开ihoneyBakFileScan备份扫描
开发语言·python
菌菌的快乐生活1 小时前
树莓派安装 OpenCV 教程
人工智能·opencv·计算机视觉
.生产的驴1 小时前
CSS 圆角渐变边框
前端·javascript·css·vue.js·python·jquery·html5