I have a QPainterPath and I want to crop an image which is QPixmap. This code worked for me but I want to use PyQt5 builtin functionality like mask without numpy
JavaScript
x
16
16
1
# read image as RGB and add alpha (transparency)
2
im = Image.open("frontal_1.jpg").convert("RGBA")
3
4
# convert to numpy (for convenience)
5
imArray = numpy.asarray(im)
6
7
# create mask
8
polygon = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]
9
10
maskIm = Image.new('L', (imArray.shape[1], imArray.shape[0]), 0)
11
ImageDraw.Draw(maskIm).polygon(polygon, outline=1, fill=1)
12
mask = numpy.array(maskIm)
13
14
newIm = Image.fromarray(newImArray, "RGBA")
15
newIm.save("out.png")
16
Advertisement
Answer
One possible way to replace mask is to use the setClipPath() method of QPainter:
JavaScript
1
18
18
1
from PyQt5 import QtCore, QtGui
2
3
if __name__ == '__main__':
4
image = QtGui.QImage('input.png')
5
output = QtGui.QImage(image.size(), QtGui.QImage.Format_ARGB32)
6
output.fill(QtCore.Qt.transparent)
7
painter = QtGui.QPainter(output)
8
9
points = [(444, 203), (623, 243), (691, 177), (581, 26), (482, 42)]
10
polygon = QtGui.QPolygonF([QtCore.QPointF(*point) for point in points])
11
12
path = QtGui.QPainterPath()
13
path.addPolygon(polygon)
14
painter.setClipPath(path)
15
painter.drawImage(QtCore.QPoint(), image)
16
painter.end()
17
output.save('out.png')
18