Python PyQt5 图片查看器:鼠标滚轮缩放、点击获取像素坐标
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QLabel, QVBoxLayout
from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtCore import Qt
class ImageViewer(QWidget):
def __init__(self, image_path):
super().__init__()
# 加载图片文件
self.image = QImage(image_path)
# 创建 QLabel 用于显示图片
self.image_label = QLabel()
self.image_label.setAlignment(Qt.AlignCenter)
self.image_label.setPixmap(QPixmap.fromImage(self.image))
# 创建布局并将图片标签添加到布局中
self.layout = QVBoxLayout()
self.layout.addWidget(self.image_label)
# 设置窗口布局
self.setLayout(self.layout)
# 设置初始缩放级别为 1
self.zoom_level = 1
# 绑定鼠标滚轮事件到 zoom 函数
self.image_label.wheelEvent = self.zoom
# 绑定鼠标点击事件到 print_pixel_coordinates 函数
self.image_label.mousePressEvent = self.print_pixel_coordinates
def zoom(self, event):
# 获取当前缩放级别
current_zoom = self.zoom_level
# 根据鼠标滚轮的滚动方向计算新的缩放级别
if event.angleDelta().y() > 0:
# 放大
self.zoom_level = current_zoom * 1.2
else:
# 缩小
self.zoom_level = current_zoom / 1.2
# 使用新的缩放级别更新图片标签
self.image_label.setPixmap(QPixmap.fromImage(self.image).scaled(self.image.width() * self.zoom_level, self.image.height() * self.zoom_level, Qt.KeepAspectRatio))
def print_pixel_coordinates(self, event):
# 获取鼠标点击的位置相对于图片标签
click_pos = event.pos()
# 获取鼠标点击的位置相对于图片
image_pos = click_pos / self.zoom_level
# 打印像素坐标
print('Pixel coordinates:', int(image_pos.x()), int(image_pos.y()))
if __name__ == '__main__':
app = QApplication(sys.argv)
# 创建图片查看器窗口
image_viewer = ImageViewer('image.jpg')
image_viewer.show()
sys.exit(app.exec_())
使用方法:
- 将代码保存为 Python 文件(例如 image_viewer.py)。
- 将您要查看的图片文件命名为 'image.jpg' 并放置在与代码文件相同的目录下。
- 运行代码。
功能说明:
- 鼠标滚轮滚动可放大或缩小图片。
- 点击图片上的任何位置,将打印出该像素点在图片上的相对坐标。
- 放大缩小图片不会影响像素点的相对坐标,即点击的像素点位置始终保持一致。
注意事项:
- 确保您的系统中已经安装了 PyQt5 库。
- 如果您使用的是其他格式的图片文件,请将代码中的 'image.jpg' 替换为您的图片文件名。
- 您可以根据需要调整代码中的缩放比例 (1.2) 和其他参数。
原文地址: https://www.cveoy.top/t/topic/nwaa 著作权归作者所有。请勿转载和采集!