简体   繁体   English

如何使用QPainterPath裁剪图像而不保存其余图像

[英]How to crop an image using QPainterPath without saving rest of image

I have a QPainterPath and I want to crop an image which is QPixmap. 我有一个QPainterPath,我想裁剪一个QPixmap的图像。 This code worked for me but I want to use PyQt5 builtin functionality like mask without numpy 这段代码对我有用,但是我想使用PyQt5内置功能,例如没有numpy的mask

# read image as RGB and add alpha (transparency)
im = Image.open("frontal_1.jpg").convert("RGBA")

# convert to numpy (for convenience)
imArray = numpy.asarray(im)

# create mask
polygon = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]

maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)
mask = numpy.array(maskIm)
...
newIm = Image.fromarray(newImArray, "RGBA")
newIm.save("out.png")

One possible way to replace mask is to use the setClipPath() method of QPainter: 替换遮罩的一种可能方法是使用QPainter的setClipPath()方法:

from PyQt5 import QtCore, QtGui

if __name__ == '__main__':
    image = QtGui.QImage('input.png')
    output = QtGui.QImage(image.size(), QtGui.QImage.Format_ARGB32)
    output.fill(QtCore.Qt.transparent)
    painter = QtGui.QPainter(output)

    points = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]
    polygon = QtGui.QPolygonF([QtCore.QPointF(*point) for point in points])

    path = QtGui.QPainterPath()
    path.addPolygon(polygon)
    painter.setClipPath(path)
    painter.drawImage(QtCore.QPoint(), image)
    painter.end()
    output.save('out.png')

After answer from above I tweaked my code a little bit and now it looks like: 从上面回答后,我对代码进行了一些调整,现在看起来像:

    path = lips_contour_path
    image = QImage('frontal_2.jpg')
    output = QImage(image.size(), QImage.Format_ARGB32)
    output.fill(Qt.transparent)
    painter = QPainter(output)
    painter.setClipPath(path)
    painter.drawImage(QPoint(), image)
    painter.end()
    # To avoid useless transparent background you can crop it like that:
    output = output.copy(path.boundingRect().toRect())
    output.save('out.png')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM