I want to draw rectangles above an QImage and save the result as png. The minimal Example below should do this.
from PyQt5.QtGui import QImage, QColor, QPainter, QBrush
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget
import sys
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "PyQt5 Drawing Tutorial"
self.top = 150
self.left = 150
self.width = 500
self.height = 500
self.mypainter = MyPainter()
self.mypainter.create()
self.InitWindow()
def InitWindow(self):
self.setWindowTitle(self.title)
self.setGeometry(self.top, self.left, self.width, self.height)
self.show()
class MyPainter(QWidget):
def __init__(self):
super().__init__()
self.img = QImage(25, 25, QImage.Format_RGBA64)
self.color1 = QColor(255, 0, 0, 255)
self.color2 = QColor(0, 255, 0, 255)
self.color3 = QColor(0, 0, 255, 255)
self.boxes = (
(2, 2, 10, 10),
(5, 5, 4, 5),
(10, 10, 10, 7))
def create(self):
self.colors = (
self.color1,
self.color2,
self.color3)
for idx, box in enumerate(self.boxes):
self.color = self.colors[idx]
self.bndboxSize = box
self.repaint()
self.img.save("myImg.png")
def paintEvent(self, event):
painter = QPainter(self)
painter.drawImage(self.rect(), self.img)
painter.setBrush(QBrush(self.color))
painter.drawRect(self.bndboxSize)
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
What I expected
The black background could also be transparent.
What I got
This is just an image with alphachannel, if your hover you will get the link
What I got (debug mode)
I have no clue how to achive the wanted image.