如何在不复制整个像素图的情况下复制pyQT QPixmaps的各个部分?

时间:2017-10-13 15:45:22

标签: python qt pyqt pyqt5

我有一个包含图块的图片。我想在QPixmap中制作每个图块的QPixmap。我认为QPixmap的copy(x,y,width,height)方法会为我做这个,但必须复制整个图像,而不仅仅是参数定义的矩形,因此消耗太多的内存。

下面的示例说明了问题。我的png恰好是3400x3078像素,除以57行,50列,迷你图应该是68x54像素,但显然使用的内存要多得多。 我错过了什么?

from PyQt5.QtGui import QPixmap
from PyQt5.QtWidgets import QApplication

import os, sys

app = QApplication(sys.argv)
file = r"/path/to/image/grid-of-tiles.png"

# image I'm using has these many rows and columns of tiles
r = 57
c = 50

pixmap = QPixmap(file)

# the tiles are known to divide evenly
width = pixmap.width() / c
height = pixmap.height() / r

# after executing the below, mem use climbs north of 9GB!
# I was expecting on the order of twice the original image's size
minipixmaps = [pixmap.copy(row*height, col*width, width, height) for row in range(r) for col in range(c)]

1 个答案:

答案 0 :(得分:0)

感谢eyllanesc的评论。 QImage确实表现得更好:

from PyQt5.QtGui import QPixmap, QImage
from PyQt5.QtWidgets import QApplication

import os, sys

app = QApplication(sys.argv)
file = r"/path/to/image/grid-of-tiles.png"

# image I'm using has these many rows and columns of tiles
r = 57
c = 50

mosaic = QImage(file) # QImage instead of QPixmap

# the tiles are known to divide evenly
width = mosaic.width() / c
height = mosaic.height() / r

# much less memory!
minipixmaps = [QPixmap.fromImage(mosaic.copy(row*height, col*width, width, height)) for row in range(r) for col in range(c)]