以下是用PyQt5实现的代码:

import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QGraphicsScene, QGraphicsView
from PyQt5.QtGui import QPixmap, QWheelEvent
from PyQt5.QtCore import Qt

class ImageViewer(QMainWindow):
    def __init__(self):
        super().__init__()

        # 创建场景和视图
        self.scene = QGraphicsScene(self)
        self.view = QGraphicsView(self.scene, self)
        self.view.setDragMode(QGraphicsView.ScrollHandDrag)
        self.view.setRenderHint(QPainter.Antialiasing)

        # 加载图片
        self.pixmap = QPixmap("image.jpg")
        self.image_item = self.scene.addPixmap(self.pixmap)

        # 设置视图大小
        self.view.setSceneRect(self.image_item.boundingRect())
        self.view.fitInView(self.image_item, Qt.KeepAspectRatio)

        # 设置窗口标题和大小
        self.setWindowTitle("Image Viewer")
        self.setGeometry(100, 100, 800, 600)

    def wheelEvent(self, event: QWheelEvent):
        # 对图片进行局部放大缩小
        factor = 1.2 if event.angleDelta().y() > 0 else 1 / 1.2
        self.view.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
        self.view.scale(factor, factor)

    def mousePressEvent(self, event):
        # 点击图片的像素点打印像素点在图片的相对坐标
        pos = event.pos()
        scene_pos = self.view.mapToScene(pos)
        image_pos = self.image_item.mapFromScene(scene_pos).toPoint()
        if self.image_item.pixmap().rect().contains(image_pos):
            pixel_value = self.image_item.pixmap().toImage().pixel(image_pos)
            print(f"Pixel value at ({image_pos.x()}, {image_pos.y()}): {pixel_value}")

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

在这个代码中,我们创建了一个名为 ImageViewer 的子类,继承自 QMainWindow。在 __init__ 方法中,我们创建了一个 QGraphicsScene 和一个 QGraphicsView 对象,用于显示图片。我们加载了一张名为 image.jpg 的图片,并将其添加到场景中。我们还设置了视图的大小和窗口的标题和大小。

wheelEvent 方法中,我们实现了鼠标滚轮对图片进行局部放大缩小的功能。我们使用 QGraphicsViewsetTransformationAnchor 方法将缩放中心点设置为鼠标位置,以便实现局部缩放。

mousePressEvent 方法中,我们实现了点击图片的像素点打印像素点在图片的相对坐标的功能。我们使用 QGraphicsViewmapToScene 方法将窗口坐标转换为场景坐标,然后使用 QGraphicsPixmapItemmapFromScene 方法将场景坐标转换为图片坐标。我们还使用 QPixmaptoImage 方法获取图片的像素值,然后打印出像素点在图片的相对坐标和像素值。

最后,在 main 函数中,我们创建了一个 QApplication 对象和一个 ImageViewer 对象,并将其显示出来

用pyqt5写一份Python代码。打开图片在特定窗口鼠标滚轮对图片局部放大缩小点击图片的像素点打印像素点在图片的相对坐标且放大缩小图片不影响像素点在图片的相对坐标

原文地址: https://www.cveoy.top/t/topic/cuJJ 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录