PyQt6/PySide6 QImage 类

PyQt6/PySide6 QImage 类详解

一、QImage 概述

QImage 是 Qt 框架中用于处理图像数据的核心类,提供:

  • 独立于硬件的图像表示
  • 像素级访问和操作
  • 多种图像格式支持(PNG/JPEG/BMP等)
  • 图像转换和基本处理功能
from PyQt6.QtGui import QImage
# 或 PySide6
from PySide6.QtGui import QImage

二、核心功能与案例

1. 创建图像对象

# 从文件加载
image = QImage("input.jpg")

# 创建空白图像
width, height = 800, 600
format = QImage.Format.Format_RGB32
image = QImage(width, height, format)  # 黑色背景

# 从字节数据创建
bytes_data = b'\xFF\x00\x00\xFF' * (width*height)
image = QImage(bytes_data, width, height, QImage.Format.Format_ARGB32)

# 从numpy数组创建(需安装numpy)
import numpy as np
arr = np.zeros((height, width, 3), dtype=np.uint8)
arr[:, :, 0] = 255  # 红色通道
image = QImage(arr.data, width, height, QImage.Format.Format_RGB888)

2. 图像基本信息

print("尺寸:", image.size())  # QSize(800, 600)
print("宽度:", image.width())
print("高度:", image.height())
print("格式:", image.format())  # Format_RGB32
print("深度:", image.depth())  # 32 bits
print("颜色模型:", image.colorModel())  # ColorModel_RGB
print("字节数:", image.sizeInBytes())

3. 像素操作

读取/修改单个像素
# 获取像素颜色(效率较低)
color = image.pixelColor(100, 50)
print(color.getRgb())  # (255, 0, 0, 255)

# 修改像素颜色
image.setPixelColor(100, 50, QColor(0, 255, 0))

# 直接操作像素值(Format_RGB32)
rgb = 0xFF00FF00  # ARGB格式
image.setPixel(100, 50, rgb)
批量像素操作(高效方式)
# 使用scanLine快速访问行数据
for y in range(image.height()):
    ptr = image.scanLine(y)
    for x in range(image.width()):
        # 假设Format_RGB32格式
        pixel = ptr[x]
        # 反转红色通道
        ptr[x] = (pixel & 0xFF00FFFF) | ((255 - ((pixel >> 16) & 0xFF)) << 16)

4. 图像转换与缩放

# 缩放图像
scaled_image = image.scaled(400, 300, 
                          aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio,
                          transformMode=Qt.TransformationMode.SmoothTransformation)

# 格式转换
gray_image = image.convertToFormat(QImage.Format.Format_Grayscale8)

# 转换为QPixmap显示
pixmap = QPixmap.fromImage(image)

5. 图像处理操作

几何变换
# 旋转45度
transform = QTransform().rotate(45)
rotated_image = image.transformed(transform)

# 水平镜像
mirrored_image = image.mirrored(horizontal=True, vertical=False)

# 裁剪
rect = QRect(100, 100, 200, 200)
cropped_image = image.copy(rect)
图像绘制
# 创建绘图对象
painter = QPainter(image)
painter.setPen(QColor(255, 0, 0))

# 绘制图形
painter.drawLine(0, 0, 100, 100)
painter.drawEllipse(50, 50, 100, 80)

# 结束绘制
painter.end()

三、高级特性

1. 图像缓存

# 设置缓存键(用于重复使用图像资源)
image.setCacheKey("unique_image_id")

2. 性能优化

# 关闭缓存(处理大图像时)
image.setCachingHint(QImage.CachingHint.DontCache)

# 使用硬件加速格式
if QImage.toImageFormat(QPixelFormat.Format_BGR30) == image.format():
    print("使用优化格式")

3. 原始数据访问

# 获取底层字节数据
ptr = image.bits()  # 可写指针
const_ptr = image.constBits()  # 只读指针

# 处理原始数据(示例:反色处理)
bytes_per_line = image.bytesPerLine()
for y in range(image.height()):
    line = const_ptr[y * bytes_per_line : (y+1) * bytes_per_line]
    # 处理每行数据...

四、综合应用案例

案例1:生成缩略图

def create_thumbnail(input_path, output_path, max_size=200):
    image = QImage(input_path)
    if image.isNull():
        return False
      
    # 计算缩放比例
    ratio = min(max_size/image.width(), max_size/image.height())
    new_size = QSize(int(image.width()*ratio), int(image.height()*ratio))
  
    # 高质量缩放
    thumbnail = image.scaled(new_size, 
                            aspectRatioMode=Qt.AspectRatioMode.KeepAspectRatio,
                            transformMode=Qt.TransformationMode.SmoothTransformation)
  
    return thumbnail.save(output_path, quality=90)

案例2:图像反色处理

def invert_image(image):
    if image.format() in [QImage.Format.Format_Indexed8, QImage.Format.Format_Grayscale8]:
        # 处理灰度图像
        for i in range(image.colorCount()):
            color = image.color(i)
            image.setColor(i, 0xFFFFFF - color)
    else:
        # 处理真彩色图像
        image.invertPixels()
    return image

案例3:屏幕截图工具

def capture_screen():
    screen = QApplication.primaryScreen()
    pixmap = screen.grabWindow(0)
    return pixmap.toImage()

# 保存截图
screenshot = capture_screen()
screenshot.save("screenshot.png")

五、注意事项

  1. 格式兼容性:不同平台对图像格式支持可能不同
  2. 性能问题:直接像素操作适合小图像,大数据量建议使用scanLine
  3. 内存管理:处理大图像时注意及时释放资源
  4. 线程安全:QImage 是可隐式共享的,但跨线程访问需要同步

六、PyQt6与PySide6差异

特性PyQt6PySide6
模块导入from PyQt6.QtGui importfrom PySide6.QtGui import
枚举访问QImage.Format_RGB32QImage.Format.RGB32
信号语法pyqtSignalSignal

通过本指南,您可全面掌握QImage的核心用法,并能实现各种图像处理需求。建议结合官方文档和实际项目进行深入实践。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值