I was able to display the first image in a label but what I'm looking for is to display all the images in the folder to be displayed side by side in a row and refresh the image automatically if there is any update. How can I create multiple labels and set images on it based on the number of image files in my folder. For example: if my folder contains image for Nicolascage, Tom Hanks, Sandra Bullocks then all their images should be placed in a row and if a new image replace the existing image then it should refresh automatically.
What I achieved so far:
My code:
import cv2,os
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from VideoFaceDetectiondup import vidcaptureface
from PyQt5 import QtCore, QtGui, QtWidgets #works for pyqt5
class MainWindow(QWidget):
def __init__(self, camera_index=0, fps=30):
super().__init__()
self.capture = cv2.VideoCapture(camera_index)
self.dimensions = self.capture.read()[1].shape[1::-1]
scene = QGraphicsScene(self)
pixmap = QPixmap(*self.dimensions)
self.pixmapItem = scene.addPixmap(pixmap)
view = QGraphicsView(self)
view.setScene(scene)
text = QLabel('facecam 1.0', self)
label = QLabel()
pixmap = QPixmap("messigray_1.png")
label.setPixmap(pixmap)
label.show()
# label.setGeometry(QtCore.QRect(1270, 1280, 1200, 1200))
layout = QVBoxLayout(self)
layout.addWidget(view)
layout.addWidget(text)
layout.addWidget(label)
timer = QTimer(self)
timer.setInterval(int(1000/fps))
timer.timeout.connect(self.get_frame)
timer.start()
def get_frame(self):
_, frame = self.capture.read()
frame=vidcaptureface(frame)
image = QImage(frame, *self.dimensions, QImage.Format_RGB888).rgbSwapped()
pixmap = QPixmap.fromImage(image)
self.pixmapItem.setPixmap(pixmap)
app = QApplication([])
win = MainWindow()
win.show()
app.exec()
Related
I'm trying to produce an onion skin effect using a QLabel in PyQt. In the simplified example below, three images are loaded in and drawn to the label using QPainter.
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QImage, QPixmap, QPainter
import sys
from pathlib import Path
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# -------------------------------------------------------------
# Define the display.
self.display = QLabel()
# -------------------------------------------------------------
# Import the frames
frame_1 = QImage(str(Path(f'fixtures/test_onion_skin/frame_{1}.png')))
frame_2 = QImage(str(Path(f'fixtures/test_onion_skin/frame_{2}.png')))
frame_3 = QImage(str(Path(f'fixtures/test_onion_skin/frame_{3}.png')))
# -------------------------------------------------------------
# Populate the display
frame_1_scaled = frame_1.scaled(self.size(), Qt.KeepAspectRatio)
frame_2_scaled = frame_2.scaled(self.size(), Qt.KeepAspectRatio)
frame_3_scaled = frame_3.scaled(self.size(), Qt.KeepAspectRatio)
base_pixmap = QPixmap(frame_1_scaled.size())
painter = QPainter(base_pixmap)
painter.drawImage(QPoint(), frame_3_scaled)
painter.setOpacity(0.5)
painter.drawImage(QPoint(), frame_2_scaled)
painter.setOpacity(0.3)
painter.drawImage(QPoint(), frame_1_scaled)
painter.end()
self.display.setPixmap(base_pixmap)
# -------------------------------------------------------------
# Set the layout.
layout = QGridLayout()
layout.addWidget(self.display, 0, 0)
self.setLayout(layout)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Ideally, the last image would show as fully opaque, with earlier images having an increasingly higher transparency. Instead, I'm getting an output where all three images blend together equally. This seems like a simple problem to fix, but my 'Google Fu' hasn't yielded much this time around.
Edit
Here are the image files. They seem have automatically been converted to .jpg unfortunately. If there's a better way to include them please let me know.
frame_1
frame_2
frame_3
Edit 2
After some experimentation I've decided to compromise and allow some 'blending' of the base image. I'm working with raw images from a camera device, so the background of each image is always going to be non-transparent.
In case anyone is interested here is the code:
from PyQt5.QtWidgets import QApplication, QWidget, QGridLayout, QLabel, QSizePolicy
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QImage, QPixmap, QPainter
import sys
from pathlib import Path
class MainWindow(QWidget):
def __init__(self):
super().__init__()
# -------------------------------------------------------------
# Define values used for image painting.
self.first_opacity = 1 # Set first image to fully opaque so it does not blend into background.
self.falloff_value = 0.15 # The opacity of the second image.
self.falloff_rate = 0.5 # A factor used to decrement subsequent image transparencies.
# -------------------------------------------------------------
# Define the display.
self.display = QLabel()
self.display.setSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.MinimumExpanding)
self.display.setMinimumSize(1, 1)
# -------------------------------------------------------------
# Import frames.
self.images = []
for i in range(1, 4, 1):
self.images.append(QImage(str(Path(f'fixtures/test_onion_skin/frame_{i}.png'))))
# -------------------------------------------------------------
# Set the display.
self.update_display()
# -------------------------------------------------------------
# Set the layout.
layout = QGridLayout()
layout.addWidget(self.display, 0, 0)
self.setLayout(layout)
def update_display(self):
# -------------------------------------------------------------
# Define the base pixmap on which to merge images.
base_pixmap = QPixmap(self.display.size())
base_pixmap.fill(Qt.transparent)
# -------------------------------------------------------------
# Preform paint cycle for images.
painter = QPainter(base_pixmap)
for (image, opacity) in zip(reversed(self.images), reversed(self.get_opacities(len(self.images)))):
painter.setOpacity(opacity)
painter.drawImage(QPoint(), image.scaled(base_pixmap.size(), Qt.KeepAspectRatio))
painter.end()
# -------------------------------------------------------------
self.display.setPixmap(base_pixmap)
def get_opacities(self, num_images):
# -------------------------------------------------------------
# Define a list to store image opacity values.
opacities = [self.first_opacity]
value = self.falloff_value
# -------------------------------------------------------------
# Calculate additional opacity values if more than one image is desired.
if num_images > 1:
num_decrements = num_images - 1
for i in range(1, num_decrements + 1, 1):
opacities.insert(0, value)
value *= self.falloff_rate
# -------------------------------------------------------------
return opacities
def resizeEvent(self, event):
self.update_display()
event.accept()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
Since the OP does not provide the images then the problem can be caused by:
The order of how opacity is set.
The background color of the image is not transparent.
For my demo I will use this gif and since the background is not transparent (which would be ideal) then I will apply a mask when I paint each image.
import os
from pathlib import Path
import sys
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QColor, QImageReader, QPainter, QPixmap, QRegion
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
CURRENT_DIRECTORY = Path(__file__).resolve().parent
class MainWindow(QWidget):
def __init__(self):
super().__init__()
self.display = QLabel(alignment=Qt.AlignCenter)
lay = QVBoxLayout(self)
lay.addWidget(self.display)
background_color = QColor("white")
filename = os.fspath(CURRENT_DIRECTORY / "Animhorse.gif")
image_reader = QImageReader(filename)
pixmap = QPixmap(image_reader.size())
pixmap.fill(background_color)
images = []
while image_reader.canRead():
images.append(image_reader.read())
painter = QPainter(pixmap)
for image, opacity in zip(images[3:6], (0.3, 0.7, 1.0)):
painter.setOpacity(opacity)
p = QPixmap.fromImage(image)
mask = p.createMaskFromColor(background_color, Qt.MaskInColor)
painter.setClipRegion(QRegion(mask))
painter.drawImage(QPoint(), image)
painter.end()
self.display.setPixmap(pixmap)
if __name__ == "__main__":
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec()
I've created a gui using PyQt5 in PyCharm and I've managed to get one QLabel with an image in it (Picture1.png) showing up, however, when I try to add a second QLabel with a second image (named Shutter1.png) on the same window, it seems to remove both labels and nothing shows up on the gui. I'm not sure where I'm going wrong and any help would be greatly appreciated, I'm a novice! NB I've doublechecked the filepath for both imagePath and imagePath_1 are correct. See below for attached code:
from PyQt5 import uic, QtWidgets, QtGui, QtCore
import sys
import pkg_resources
import functions.initialisation as inits
import functions.Sig2Open as S2O
import functions.Sig2Close as S2C
class Ui(QtWidgets.QMainWindow):
def __init__(self):
super(Ui, self).__init__()
self.gui = uic.loadUi('Shuttergui.ui', self)
# Creates the path of the image
self.imagePath = "C:/........../Picture1.png"
self.label = QtWidgets.QLabel(self.gui)
self.image = QtGui.QImage(self.imagePath)
self.pixmapImage = QtGui.QPixmap.fromImage(self.image)
self.label.setPixmap(self.pixmapImage)
self.label.resize(self.width(), self.height())
self.label.move(60, 170)
self.imagePath = "C:/....../Shutter1.png"
# Create label that holds the image in imagePath
self.label_1 = QtWidgets.QLabel(self.gui)
self.image_1 = QtGui.QImage(self.imagePath)
self.pixmapImage_1 = QtGui.QPixmap.fromImage(self.image_1)
self.label_1.setPixmap(self.pixmapImage_1)
self.label_1.resize(self.width(), self.height())
self.label_1.move(60, 170)
self.gui.showMaximized()
# redirect closeevent func to main self rather than inside gui
self.gui.closeEvent = self.closeEvent
# Initialise shutter functions
inits.ardopenup(self)
inits.ardshutup(self)
self.gui.show()
def closeEvent(self, event):
import time
time.sleep(0.1)
print("main thread quitting")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
app.setStyleSheet(pkg_resources.resource_stream(__name__, '/css/darktheme/style.css').read().decode())
window = Ui()
sys.exit(app.exec_())
I would like to ask how do I go about including a folium map into PyQt 5 window application such that the map does not take up the whole window. I have found a similar post on StackOverflow "How to show Folium map inside a PyQt5 GUI?", however, the solution code provided shown the folium map takes up the whole of the PyQt 5 window application.
So my question is how do I include the folium map but only takes up a portion of the PyQt 5 window application? As shown below, I am trying to include the map into the rectangle area. *The rectangle black box is drawn on paint for reference purposes.
FYI I have tried out the solution code from the StackOverflow post but I can't seem to be able to resize the map.
WANTED OUTPUT
CURRENT CODE FOR REFERENCE
from PyQt5.QtWidgets import QMainWindow, QApplication, QPushButton
from PyQt5 import QtWebEngineWidgets
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import QRect
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.title = "MAP PROJECT"
self.left = 200
self.top = 100
self.width = 1500
self.height = 800
self.initWindow()
def initWindow(self):
# set window title
self.setWindowTitle(self.title)
# set window geometry
# self.setGeometry(self.left, self.top, self.width, self.height)
# Disable PyQt 5 application from resizing
self.setFixedSize(self.width, self.height)
self.buttonUI()
self.show()
def buttonUI(self):
shortPathButton = QPushButton("Find shortest path", self)
# (set button location (x, x) set button size (y, y)
shortPathButton.setGeometry(QRect(30, 300, 120, 50))
button2 = QPushButton("Another path", self)
# (set button location (x, x) set button size (y, y)
button2.setGeometry(QRect(30, 370, 120, 50))
button3 = QPushButton("Another path", self)
# (set button location (x, x) set button size (y, y)
button3.setGeometry(QRect(30, 440, 120, 50))
# Below code is to connect the button to the function
# button.clicked.connect(self.ClickMe)
# Create function for shortest path (A* algorithm)
"""def ClickMe(self):
print("Hello World")"""
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
The problem has nothing to do with a QWebEngineView or folium but how to place widgets inside the window, if so, then a solution is to use layouts in this case I will use the following structure: First a central widget is established, inside this one QHBoxLayout , and in the QHBoxLayout a QWidget is added as a container to the left side where a QVBoxLayout will be placed where the buttons will be, and to the right side the QWebEngineView:
import io
import sys
import folium
from PyQt5 import QtCore, QtGui, QtWidgets, QtWebEngineWidgets
class Window(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.initWindow()
def initWindow(self):
self.setWindowTitle(self.tr("MAP PROJECT"))
self.setFixedSize(1500, 800)
self.buttonUI()
def buttonUI(self):
shortPathButton = QtWidgets.QPushButton(self.tr("Find shortest path"))
button2 = QtWidgets.QPushButton(self.tr("Another path"))
button3 = QtWidgets.QPushButton(self.tr("Another path"))
shortPathButton.setFixedSize(120, 50)
button2.setFixedSize(120, 50)
button3.setFixedSize(120, 50)
self.view = QtWebEngineWidgets.QWebEngineView()
self.view.setContentsMargins(50, 50, 50, 50)
central_widget = QtWidgets.QWidget()
self.setCentralWidget(central_widget)
lay = QtWidgets.QHBoxLayout(central_widget)
button_container = QtWidgets.QWidget()
vlay = QtWidgets.QVBoxLayout(button_container)
vlay.setSpacing(20)
vlay.addStretch()
vlay.addWidget(shortPathButton)
vlay.addWidget(button2)
vlay.addWidget(button3)
vlay.addStretch()
lay.addWidget(button_container)
lay.addWidget(self.view, stretch=1)
m = folium.Map(
location=[45.5236, -122.6750], tiles="Stamen Toner", zoom_start=13
)
data = io.BytesIO()
m.save(data, close_file=False)
self.view.setHtml(data.getvalue().decode())
if __name__ == "__main__":
App = QtWidgets.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(App.exec())
I would like to place a QPixmap on another QPixmap. Both have the same size, so I would just like to make an overlay. The overlay image has a transparent elipse in the middle. I figure they should be QPixmap format, however I dont know how to place them on top of each other and keep them in place when resizing the window. This is my code displaying how my background images are placed. I have attached a image explaining what i want.
import sys
from PyQt5 import QtGui ,QtWidgets, uic
from PyQt5.QtCore import Qt
class Ergolab(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(Ergolab, self).__init__(*args, **kwargs)
# Load the UI Page
self.ui = uic.loadUi("mainwindow.ui",self)
self.pixmap1 = QtGui.QPixmap('C:/Users/Frede/Desktop/img1.jpg')
self.shoflexLLabel.setPixmap(self.pixmap1.scaled(self.shoflexLLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.shoflexLLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.shoflexLLabel.setMinimumSize(150, 150)
self.shoflexLLabel.resize(800, 600)
self.pixmap2 = QtGui.QPixmap('C:/Users/Frede/Desktop/img2.jpg')
self.shoflexRLabel.setPixmap(self.pixmap2.scaled(self.shoflexRLabel.size(), Qt.KeepAspectRatio, Qt.SmoothTransformation))
self.shoflexRLabel.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
self.shoflexRLabel.setMinimumSize(150, 150)
self.shoflexRLabel.resize(800, 600)
def resizeEvent(self, event):
scaledSize = self.shoflexLLabel.size()
if not self.shoflexLLabel.pixmap() or scaledSize != self.shoflexLLabel.pixmap().size():
self.updateLabel()
def updateLabel(self):
self.shoflexLLabel.setPixmap(self.pixmap1.scaled(
self.shoflexLLabel.size(), Qt.KeepAspectRatio,
Qt.SmoothTransformation))
self.shoflexRLabel.setPixmap(self.pixmap2.scaled(
self.shoflexRLabel.size(), Qt.KeepAspectRatio,
Qt.SmoothTransformation))
def main():
app = QtWidgets.QApplication(sys.argv)
main = Ergolab()
main.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
This is the result I would like:
You must use QPainter by setting the circle as a clip path:
import sys
from PyQt5 import QtCore, QtGui, QtWidgets
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
label = QtWidgets.QLabel()
self.setCentralWidget(label)
base_pixmap = QtGui.QPixmap("background.png")
overlay_pixmap = QtGui.QPixmap("overlay.png")
radius = 300
r = QtCore.QRectF()
r.setSize(radius * QtCore.QSizeF(1, 1))
r.moveCenter(base_pixmap.rect().center())
path = QtGui.QPainterPath()
path.addEllipse(r)
painter = QtGui.QPainter(base_pixmap)
painter.setRenderHints(
QtGui.QPainter.Antialiasing | QtGui.QPainter.SmoothPixmapTransform
)
painter.setClipPath(path, QtCore.Qt.IntersectClip)
painter.drawPixmap(QtCore.QPoint(), overlay_pixmap)
painter.end()
label.setPixmap(base_pixmap)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
I created a file using QT Designer, and I uploaded a background image. This file works well and the image appears in the background.
However, when the file is import to the main file, the image does not appear in the background correctly.
and project link
https://github.com/ahmedlam3y/GarageSystem
Because it is not the main window, but it is Ù‹Widget so the picture was not visible in the background and one of the Widgets has been set to the mainWindow so it work correctly
and The code for solution:
import sys
from PyQt5.QtCore import QSize
from PyQt5 import QtCore, QtGui, QtWidgets as Q
from PyQt5.QtGui import QImage, QPalette, QBrush
from PyQt5.QtWidgets import *
import image_rc
from SignIN import Ui_Form as SignInForm
from WelFrame import Ui_Form as WelFrameForm
from SignUp import Ui_Form as SignUpForm
from Accounting import Ui_Form as AccountForm
class SignIn(Q.QWidget, SignInForm): # Widget
def __init__(self, parent=None):
super(SignIn, self).__init__(parent)
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
class WelFrame(Q.QMainWindow, WelFrameForm): # MainWindow
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
class SignUp(Q.QWidget, SignUpForm): # Widget
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
class Accout(Q.QWidget, AccountForm): # Widget
def __init__(self, parent=None):
Q.QWidget.__init__(self, parent)
self.setupUi(self)
oImage = QImage("GTR.png")
sImage = oImage.scaled(QSize(600, 360)) # resize Image to widgets size
palette = QPalette()
palette.setBrush(10, QBrush(sImage)) # 10 = WindowRole
self.setPalette(palette)
def foo(w1, w2):
w1.show()
w2.hide()
if __name__ == '__main__':
app = Q.QApplication(sys.argv)
wel = WelFrame()
signIn = SignIn()
signUp = SignUp()
accout = AccountForm()
wel.pushButton_2.clicked.connect(lambda: foo(signIn, wel))
wel.pushButton.clicked.connect(lambda: foo(signUp, wel))
signIn.pushButton_2.clicked.connect(lambda: foo(wel, signIn))
signUp.pushButton_2.clicked.connect(lambda: foo(wel, signUp))
wel.show()
sys.exit(app.exec_())