PyQt5 проблема связки интерфейса с кодом
Проблема в этой строчке кода, не удается передать путь к файлу через переменную w.res:
def btncrypt(self):
self.i = self.textEdit.toPlainText()
input_main(f_name= w.res)
когда я меняю w.res на полный путь к файлу
"/home/mazafaker/python/SUPER PROJECT v228/project stegano/v1.mp4"
def btncrypt(self):
self.i = self.textEdit.toPlainText()
input_main(f_name= "/home/mazafaker/python/SUPER PROJECT v228/project stegano/v1.mp4")
когда задаю полный путь, то все работает.
Не могу понять, почему переменная res не может передать путь файлу
выдает ошибку:
Traceback (most recent call last):
File "/home/mazafaker/python/SUPER PROJECT v228/project stegano/main.py", line 238, in btncrypt
input_main(f_name= w.res)
File "/home/mazafaker/python/SUPER PROJECT v228/project stegano/main.py", line 157, in input_main
frame_extraction(f_name)
File "/home/mazafaker/python/SUPER PROJECT v228/project stegano/main.py", line 112, in frame_extraction
vidcap = cv2.VideoCapture(video)
cv2.error: OpenCV(4.5.4-dev) :-1: error: (-5:Bad argument) in function 'VideoCapture'
> Overload resolution failed:
> - Can't convert object of type 'tuple' to 'str' for 'filename'
> - VideoCapture() missing required argument 'apiPreference' (pos 2)
> - Argument 'index' is required to be an integer
> - VideoCapture() missing required argument 'apiPreference' (pos 2)
полный код:
# импортируемые модули для проекта
import os,sys
import pathlib
import wave
import numpy as np
import math
import cv2
import shutil
from math import ceil
from subprocess import call,STDOUT
from tqdm import tqdm
from stegano import lsb
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog, QPushButton, QMainWindow, QLabel
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(439, 376)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(20, 210, 241, 17))
self.label_2.setStyleSheet("font: 9pt \"Ubuntu\";")
self.label_2.setObjectName("label_2")
self.browse = QtWidgets.QPushButton(self.centralwidget)
self.browse.setGeometry(QtCore.QRect(250, 230, 89, 25))
self.browse.setObjectName("browse")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(30, 300, 371, 23))
self.progressBar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.progressBar.setAutoFillBackground(False)
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.logo = QtWidgets.QLabel(self.centralwidget)
self.logo.setGeometry(QtCore.QRect(90, -10, 251, 81))
self.logo.setText("")
self.logo.setPixmap(QtGui.QPixmap("./logo.png"))
self.logo.setObjectName("logo")
self.filename = QtWidgets.QLineEdit(self.centralwidget)
self.filename.setGeometry(QtCore.QRect(20, 230, 221, 25))
self.filename.setObjectName("filename")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(0, 260, 441, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(20, 110, 221, 71))
self.textEdit.setObjectName("textEdit")
self.btncryptmsg = QtWidgets.QPushButton(self.centralwidget)
self.btncryptmsg.setGeometry(QtCore.QRect(280, 120, 141, 61))
self.btncryptmsg.setStyleSheet("font: 10pt \"Ubuntu\";")
self.btncryptmsg.setObjectName("btncryptmsg")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(-20, 60, 471, 20))
self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(20, 90, 161, 17))
self.label_4.setStyleSheet("font: 9pt \"Ubuntu\";")
self.label_4.setObjectName("label_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 439, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "Укажите путь к файлу:"))
self.browse.setText(_translate("MainWindow", "Обзор..."))
self.btncryptmsg.setText(_translate("MainWindow", "зашифровать текст "))
self.label_4.setText(_translate("MainWindow", "Введите сообщение"))
# Function to split the message.
def split_string(split_str,count=10):
per_c=math.ceil(len(split_str)/count)
c_cout=0
out_str=''
split_list=[]
for s in split_str:
out_str+=s
c_cout+=1
if c_cout == per_c:
split_list.append(out_str) # The message is divided into substrings
out_str=''
c_cout=0
if c_cout!=0:
split_list.append(out_str)
return split_list
# As we know video is a collection of frames, where each frame is a picture.
# This function will extract each frame along with audio from the video.
def frame_extraction(video):
if not os.path.exists("./temp"):
os.makedirs("temp")
temp_folder="./temp" # Temporary folder created to store the frames and audio from the video.
print("[INFO] temp directory is created")
vidcap = cv2.VideoCapture(video)
count = 0
while True:
success, image = vidcap.read()
if not success:
break
cv2.imwrite(os.path.join(temp_folder, "{:d}.png".format(count)), image)
count += 1
# This function would embed the splitted string into the frames extracted from the video.
def encode_string(input_string,root="./temp/"):
split_string_list=split_string(input_string) # Acquire the splitted string from the message.
for i in range(0,len(split_string_list)):
f_name="{}{}.png".format(root,i)
secret_enc=lsb.hide(f_name,split_string_list[i]) # Вставка разделенной строки в каждый кадр.
secret_enc.save(f_name) # Сохранил кадры после сокрытия строк.
print("[INFO] frame {} holds {}".format(f_name,lsb.reveal(f_name)))
print("Сообщение хранится в файле Embedded_Video.mp4 ")
# This function would decode the hidden message by extracting frames from the video
def decode_string(video):
frame_extraction(video) # Extracting each frame from the video
secret=[]
root="./temp/"
for i in range(len(os.listdir(root))):
f_name="{}{}.png".format(root,i)
secret_dec=lsb.reveal(f_name) # Revealing the message inside each string
if secret_dec == None:
break
secret.append(secret_dec)
print(''.join([i for i in secret]))
clean_temp()
# This function would delete the temp directory
def clean_temp(path="./temp"):
if os.path.exists(path):
shutil.rmtree(path)
print("[INFO] temp files are cleaned up")
# This function would extraxt audio from the video so as to stitch them back later.
def input_main(f_name):
input_string = w.i
frame_extraction(f_name)
# The call function would be used to extract the audio and then stitch it again properly with the frames extracted.
call(["ffmpeg", "-i",f_name, "-q:a", "0", "-map", "utf-8", "a", "temp/audio.mp3", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
encode_string(input_string)
call(["ffmpeg", "-i", "temp/%d.png" , "-vcodec", "utf-8", "png", "temp/Embedded_Video.mp4", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
call(["ffmpeg", "-i", "temp/Embedded_Video.mp4", "utf-8", "-i", "temp/audio.mp3", "-codec", "copy", "Embedded_Video.mp4", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
clean_temp()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
# !!! тут логика
self.btncryptmsg.clicked.connect(self.btncrypt)
self.browse.clicked.connect(self.clicker) # !!!
def clicker(self): # !!!
self.res = QFileDialog.getOpenFileName(self, 'Open File', './')
self.filename.setText(self.res[0])
def btncrypt(self):
self.i = self.textEdit.toPlainText()
input_main(f_name= w.res)
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
uw = Ui_MainWindow()
w.show()
sys.exit(app.exec())
Ответы (1 шт):
Автор решения: S. Nick
→ Ссылка
w.res - это кортеж.
Правильно делать так:
import os,sys
import pathlib
import wave
import numpy as np
import math
import cv2
import shutil
from math import ceil
from subprocess import call,STDOUT
from tqdm import tqdm
# ???from stegano import lsb
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets import QDialog, QApplication, QFileDialog, QPushButton, QMainWindow, QLabel
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(439, 376)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.centralwidget.setObjectName("centralwidget")
self.label_2 = QtWidgets.QLabel(self.centralwidget)
self.label_2.setGeometry(QtCore.QRect(20, 210, 241, 17))
self.label_2.setStyleSheet("font: 9pt \"Ubuntu\";")
self.label_2.setObjectName("label_2")
self.browse = QtWidgets.QPushButton(self.centralwidget)
self.browse.setGeometry(QtCore.QRect(250, 230, 89, 25))
self.browse.setObjectName("browse")
self.progressBar = QtWidgets.QProgressBar(self.centralwidget)
self.progressBar.setGeometry(QtCore.QRect(30, 300, 371, 23))
self.progressBar.setLayoutDirection(QtCore.Qt.LeftToRight)
self.progressBar.setAutoFillBackground(False)
self.progressBar.setProperty("value", 24)
self.progressBar.setObjectName("progressBar")
self.logo = QtWidgets.QLabel(self.centralwidget)
self.logo.setGeometry(QtCore.QRect(90, -10, 251, 81))
self.logo.setText("")
self.logo.setPixmap(QtGui.QPixmap("./logo.png"))
self.logo.setObjectName("logo")
self.filename = QtWidgets.QLineEdit(self.centralwidget)
self.filename.setGeometry(QtCore.QRect(20, 230, 221, 25))
self.filename.setObjectName("filename")
self.line = QtWidgets.QFrame(self.centralwidget)
self.line.setGeometry(QtCore.QRect(0, 260, 441, 20))
self.line.setFrameShape(QtWidgets.QFrame.HLine)
self.line.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line.setObjectName("line")
self.textEdit = QtWidgets.QTextEdit(self.centralwidget)
self.textEdit.setGeometry(QtCore.QRect(20, 110, 221, 71))
self.textEdit.setObjectName("textEdit")
self.btncryptmsg = QtWidgets.QPushButton(self.centralwidget)
self.btncryptmsg.setGeometry(QtCore.QRect(280, 120, 141, 61))
self.btncryptmsg.setStyleSheet("font: 10pt \"Ubuntu\";")
self.btncryptmsg.setObjectName("btncryptmsg")
self.line_2 = QtWidgets.QFrame(self.centralwidget)
self.line_2.setGeometry(QtCore.QRect(-20, 60, 471, 20))
self.line_2.setFrameShape(QtWidgets.QFrame.HLine)
self.line_2.setFrameShadow(QtWidgets.QFrame.Sunken)
self.line_2.setObjectName("line_2")
self.label_4 = QtWidgets.QLabel(self.centralwidget)
self.label_4.setGeometry(QtCore.QRect(20, 90, 161, 17))
self.label_4.setStyleSheet("font: 9pt \"Ubuntu\";")
self.label_4.setObjectName("label_4")
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtWidgets.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 439, 22))
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtWidgets.QStatusBar(MainWindow)
self.statusbar.setObjectName("statusbar")
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
_translate = QtCore.QCoreApplication.translate
MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
self.label_2.setText(_translate("MainWindow", "Укажите путь к файлу:"))
self.browse.setText(_translate("MainWindow", "Обзор..."))
self.btncryptmsg.setText(_translate("MainWindow", "зашифровать текст "))
self.label_4.setText(_translate("MainWindow", "Введите сообщение"))
# Function to split the message.
def split_string(split_str,count=10):
per_c=math.ceil(len(split_str)/count)
c_cout=0
out_str=''
split_list=[]
for s in split_str:
out_str+=s
c_cout+=1
if c_cout == per_c:
split_list.append(out_str) # The message is divided into substrings
out_str=''
c_cout=0
if c_cout!=0:
split_list.append(out_str)
return split_list
# As we know video is a collection of frames, where each frame is a picture.
# This function will extract each frame along with audio from the video.
def frame_extraction(video):
if not os.path.exists("./temp"):
os.makedirs("temp")
temp_folder="./temp" # Temporary folder created to store the frames and audio from the video.
print("[INFO] temp directory is created")
# ??? TypeError: an integer is required (got type tuple)
# TypeError: требуется целое число (получен кортеж типа)
vidcap = cv2.VideoCapture(video)
count = 0
while True:
success, image = vidcap.read()
if not success:
break
cv2.imwrite(os.path.join(temp_folder, "{:d}.png".format(count)), image)
count += 1
# This function would embed the splitted string into the frames extracted from the video.
def encode_string(input_string,root="./temp/"):
split_string_list=split_string(input_string) # Acquire the splitted string from the message.
for i in range(0,len(split_string_list)):
f_name="{}{}.png".format(root,i)
secret_enc=lsb.hide(f_name,split_string_list[i]) # Вставка разделенной строки в каждый кадр.
secret_enc.save(f_name) # Сохранил кадры после сокрытия строк.
print("[INFO] frame {} holds {}".format(f_name,lsb.reveal(f_name)))
print("Сообщение хранится в файле Embedded_Video.mp4 ")
# This function would decode the hidden message by extracting frames from the video
def decode_string(video):
frame_extraction(video) # Extracting each frame from the video
secret=[]
root="./temp/"
for i in range(len(os.listdir(root))):
f_name="{}{}.png".format(root,i)
secret_dec=lsb.reveal(f_name) # Revealing the message inside each string
if secret_dec == None:
break
secret.append(secret_dec)
print(''.join([i for i in secret]))
clean_temp()
# This function would delete the temp directory
def clean_temp(path="./temp"):
if os.path.exists(path):
shutil.rmtree(path)
print("[INFO] temp files are cleaned up")
# This function would extraxt audio from the video so as to stitch them back later.
def input_main(f_name):
print(f'f_name = `{f_name}`') # +++
input_string = w.i
frame_extraction(f_name)
# The call function would be used to extract the audio and then stitch it again properly with the frames extracted.
call(["ffmpeg", "-i",f_name, "-q:a", "0", "-map", "utf-8", "a", "temp/audio.mp3", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
encode_string(input_string)
call(["ffmpeg", "-i", "temp/%d.png" , "-vcodec", "utf-8", "png", "temp/Embedded_Video.mp4", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
call(["ffmpeg", "-i", "temp/Embedded_Video.mp4", "utf-8", "-i", "temp/audio.mp3", "-codec", "copy", "Embedded_Video.mp4", "-y"],stdout=open(os.devnull, "w"), stderr=STDOUT)
clean_temp()
class MainWindow(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self):
super().__init__()
self.setupUi(self)
self.res = None # !!!
# !!! тут логика
self.btncryptmsg.clicked.connect(self.btncrypt)
self.browse.clicked.connect(self.clicker)
def clicker(self):
self.res, ok = QFileDialog.getOpenFileName( # !!! + ok
self,
'Open File',
'./',
'(*.mp4)'
)
if self.res: # +++
self.filename.setText(self.res) # !!! - [0]
def btncrypt(self):
self.i = self.textEdit.toPlainText()
# input_main(f_name=w.res)
if self.res: # +++
self.textEdit.setPlainText(self.res)
QtWidgets.QApplication.processEvents()
input_main(self.res) # +++
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
# uw = Ui_MainWindow() # --- # +++
w.show()
sys.exit(app.exec())
