Qt如何去除漫画大图中的棋盘格图案?
解决QGraphicsView缩放黑白漫画时出现的棋盘格伪影
你遇到的棋盘格图案是图像缩放时的采样伪影——Qt默认对像素图使用最近邻插值算法,黑白图像缩小后,相邻的黑白像素会交替显示,形成类似棋盘格的效果。专业图像查看器通过使用更平滑的插值算法避免这种问题,以下是几种Qt中的实现方案:
方法1:给QGraphicsView启用平滑渲染提示
这是最简单的解决方案,直接让视图渲染像素图时使用平滑插值:
from PySide6 import QtWidgets from PySide6 import QtGui from PySide6 import QtCore app = QtWidgets.QApplication() view = QtWidgets.QGraphicsView() # 启用平滑像素变换,替换默认的最近邻插值 view.setRenderHint(QtGui.QPainter.SmoothPixmapTransform) scene = QtWidgets.QGraphicsScene() item = QtWidgets.QGraphicsPixmapItem(QtGui.QPixmap("path/to/image")) scene.addItem(item) view.setScene(scene) view.fitInView(item, QtCore.Qt.AspectRatioMode.KeepAspectRatio) view.show() app.exec()
方法2:预先缩放像素图时指定平滑模式
如果需要提前处理图像尺寸(比如适配视图大小),可以在缩放QPixmap时明确使用平滑变换:
from PySide6 import QtWidgets from PySide6 import QtGui from PySide6 import QtCore app = QtWidgets.QApplication() view = QtWidgets.QGraphicsView() scene = QtWidgets.QGraphicsScene() # 加载原始像素图 original_pixmap = QtGui.QPixmap("path/to/image") # 获取视图视口尺寸作为目标缩放尺寸 target_size = view.viewport().size() # 使用平滑插值缩放,保持宽高比 smoothed_pixmap = original_pixmap.scaled( target_size, QtCore.Qt.KeepAspectRatio, QtCore.Qt.SmoothTransformation ) item = QtWidgets.QGraphicsPixmapItem(smoothed_pixmap) scene.addItem(item) view.setScene(scene) view.fitInView(item, QtCore.Qt.AspectRatioMode.KeepAspectRatio) view.show() app.exec()
方法3:自定义QGraphicsPixmapItem控制绘制逻辑
如果需要更灵活的渲染控制,可以重写QGraphicsPixmapItem的paint方法,强制使用平滑插值:
from PySide6 import QtWidgets from PySide6 import QtGui from PySide6 import QtCore class SmoothPixmapItem(QtWidgets.QGraphicsPixmapItem): def paint(self, painter, option, widget=None): # 启用平滑像素变换 painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True) super().paint(painter, option, widget) app = QtWidgets.QApplication() view = QtWidgets.QGraphicsView() scene = QtWidgets.QGraphicsScene() item = SmoothPixmapItem(QtGui.QPixmap("path/to/image")) scene.addItem(item) view.setScene(scene) view.fitInView(item, QtCore.Qt.AspectRatioMode.KeepAspectRatio) view.show() app.exec()
补充说明
SmoothPixmapTransform在不同平台/Qt版本下会使用双线性或双三次插值,能有效消除黑白图像缩小后的棋盘格伪影。- 如果极端场景下仍有残留,可以尝试先将图像转换为
QImage并应用高斯模糊预滤波后再缩放,但一般前三种方法已足够解决问题。
内容的提问来源于stack exchange,提问作者Neat
相关产品推荐
相关产品推荐

