python+Qt5 UOS 摄相头+麦克风测试,摄相头自动解析照片二维条码,麦克风解析音频文件

UI图片:

源代码:

python 复制代码
# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'CameraTestFrm.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again.  Do not edit this file unless you know what you are doing.


import time
import sys
import cv2
from PyQt5.QtCore import QTimer, pyqtSlot, Qt
from PyQt5.QtGui import QImage, QPixmap
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout, QLabel
#pip install opencv-python PyQt5
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
import logging
import os
import json
import configparser
from PyQt5.QtCore import pyqtSignal
#sudo apt-get update
#sudo apt-get install libzbar0
#pip install opencv-python pyzbar解析二维条码
from pyzbar import pyzbar#解析二维条码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import pyaudio
import wave
import threading
#录音测试及解析音频文件库
#pip install PyAudio
#pip install SpeechRecognition
#pip install matplotlib

from queue import Queue
from threading import Thread
import librosa
from scipy.fftpack import fft
from scipy import signal
#pip install scipy
import shutil
import platform
import subprocess


class Ui_CameraTestFrm(QWidget):
    update_waveform_signal = pyqtSignal(np.ndarray, np.ndarray)  # 新增信号,用于更新波形显示
    def __init__(self):
        super().__init__()
        self.config=configparser.ConfigParser()#创建对象
        self.itemName=''#项目名称
        self.testArgs=[]#测试参数信息
        self.testStandardArgs = ''  # 测试准标参数
        self.Err=''#错误信息
        self.isTestCamera=False #是否测试摄相头状态
        self.isTestRecord=False #是否测试麦克风
        self.lock = threading.Lock()  # 添加线程锁
        self.sn=''#sn信息

        #配置读取信息
        self.frequency_Tolerance=0#音频频率容差
        self.Image_Info='test'#解析照片内容
        self.CameraImagePath=''#摄相头采集照片上传服务器路径
        self.Recorded_AudioPath=''#麦克风测试采集文件上传服务器路径
        self.user=''#共享目录帐号
        self.pwd=''#共享目录密码

        #测试状况
        self.isCameraTestPass=False#摄头测试是否PASS
        self.isRecordTestPass=False#麦克风测试是否PASS
        self.cameraTestValues=''#摄相头采集的数据
        self.recordTestValues=0#麦克风采集的值

        # 生成日志信息
        self.logger = logging.getLogger('my_logger')  # 步骤1 创建日志记录器
        self.logger.setLevel(logging.DEBUG)  # 步骤2 将指定日志级别
        self.file_handler = logging.FileHandler('./log/log.txt')  # 步骤3 创建文件处理器
        self.formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')  # 步骤4 创建格式化器
        self.file_handler.setFormatter(self.formatter)  # 步骤4 将格式化器添加到处理器
        self.logger.addHandler(self.file_handler)  # 步骤5 将处理器添加到日志记录器

        # 读取配置
        self.config.read('./Conf/config.conf', encoding='utf-8')  # 读取配置文件,如果配置文件不存在则创建
        self.ReadJsonSnInfo('./Conf/OrderInfo.json', 'SN')#读取订单信息中SN条码信息

        # 读取测试配置
        self.itemName = self.config.get('TestItemNameArrays', 'CameraTest')
        self.itemFailSleepExit = int(self.config.get('TestItemWinFrmSleepExit', 'CameraTest'))  # 项目测试Fail延时退出
        self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')  # 读取测试参数信息
        self.frequency_Tolerance=int(self.config.get('CameraTest','Frequency_Tolerance'))#采集音频频率容差
        self.Image_Info=self.config.get('CameraTest','Image_Info')#采集图片解析的内容
        self.CameraImagePath=self.config.get('CameraTest','CameraImagePath')#照片文件上传服务器路径
        self.Recorded_AudioPath=self.config.get('CameraTest','Recorded_AudioPath')#音频文件上传服务器路径
        self.user =self.config.get('CameraTest','user')#服务器共享目录帐号
        self.pwd=self.config.get('CameraTest','password')#服务器共享目录密码

        self.setupUi()  # 绘制UI
        if self.ReadJsonTestArgs(self.itemName)==True:#获取标准参数
            self.lbl_CurrentSwTest.setText('测试参数获取中..')
            testArgs=[]#测试参数
            testArgs=self.testStandardArgs.split('|')
            if 'True' in testArgs[0][testArgs[0].find('=')+1:]:
                self.isTestCamera=True
                self.label_8.setText('True')
            else:
                self.isTestCamera=False
                self.label_8.setText('False')

            if 'True' in testArgs[1][testArgs[1].find('=')+1:]:
                self.isTestRecord=True
                self.label_11.setText('True')
            else:
                self.isTestRecord=False
                self.label_11.setText('False')

            #判断是否测试摄相头
            if self.isTestCamera:
                self.lbl_CurrentSwTest.setText('开始摄相头测试..')
                self.initCamera()
            if self.isTestRecord:
                self.lbl_CurrentSwTest.setText('开始麦克风测试..')
                self.update_waveform_signal.connect(self.update_waveform)
                self.audio_queue = Queue()  # 创建一个队列用于存储录音数据
                self.is_recording = False  # 设置一个标志,用于控制录音线程
                self.running = True

                # ...其余初始化代码...
                self.audio_data_buffer = None  # 用于存储最新的音频数据
                self.update_timer = QTimer(self)  # 创建定时器
                self.update_timer.timeout.connect(self.update_waveform_on_timer)  # 连接定时器信号
                self.update_timer.start(100)  # 设置定时器间隔,例如100ms

                self.start_realtime_audio_processing()  # 启动实时音频处理

            #判断最终测试结果时钟
            # 创建一个定时器来检查视频是否播放结束
            self.testReuslttimer = QTimer(self)
            self.testReuslttimer.setInterval(1000)  # 每秒检查一次
            self.testReuslttimer.timeout.connect(self.check_Test)
            self.testReuslttimer.start()

    def initCamera(self):
        # 初始化摄像头
        self.capture = cv2.VideoCapture(0)
        if not self.capture.isOpened():
            self.ShowLog("无法启动摄像头", False)
            self.label_6.setText('FAIL')
            self.label_6.setStyleSheet("color: red;")
        else:
            # 设置定时器更新摄像头画面
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.updateFrame)
            self.timer.start(20)

            # 创建用于定期捕获和解析图像的定时器
            self.captureTimer = QTimer(self)
            self.captureTimer.timeout.connect(self.captureAndDecodeImage)
            self.captureTimer.start(1000)  # 设置为1秒

    @pyqtSlot()
    def updateFrame(self):
        ret, self.image = self.capture.read()
        self.image = cv2.flip(self.image, 1)
        self.displayImage(self.image, 1)

    def displayImage(self, img, window=1):
        qformat = QImage.Format_Indexed8
        if len(img.shape) == 3:  # 如果是彩色图像
            if img.shape[2] == 4:  # 如果是4通道(RGBA)
                qformat = QImage.Format_RGBA8888
            else:  # 如果是3通道(RGB)
                qformat = QImage.Format_RGB888

        outImage = QImage(img, img.shape[1], img.shape[0], img.strides[0], qformat)
        outImage = outImage.rgbSwapped()  # 对于RGB图像进行颜色转换

        if window == 1:
            self.image_label.setPixmap(QPixmap.fromImage(outImage))
            self.image_label.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter)

    #照片采集
    def captureImage(self):
        flag, frame = self.capture.read()
        frame = cv2.flip(frame, 1)
        cv2.imwrite('captured_image.jpg', frame)
        self.ShowLog("图形采集中..", False)
        #print("Image saved!")

    def update_waveform_on_timer(self):
        """定时器回调函数,用于更新波形图"""
        if self.audio_data_buffer is not None:
            signal = np.frombuffer(self.audio_data_buffer, dtype='int16')
            framerate = 44100
            time = np.linspace(0., len(signal) / framerate, num=len(signal))
            self.update_waveform(time, signal)
            self.audio_data_buffer = None  # 重置音频数据缓冲区

    def update_waveform(self, time_array, signal_array):
        """
        更新音频波形显示。
        :param time_array: NumPy数组,表示时间点。
        :param signal_array: NumPy数组,表示信号强度。
        """
        # 首先清除布局中的所有旧子项
        while self.QVB_LyRecord.count():
            child = self.QVB_LyRecord.takeAt(0)
            if child.widget():
                child.widget().deleteLater()

        # 生成波形图
        fig, ax = plt.subplots()
        ax.plot(time_array, signal_array)
        ax.set_xlabel('Time [s]')
        ax.set_ylabel('Amplitude')

        # 将波形图添加到UI布局中
        canvas = FigureCanvas(fig)
        self.QVB_LyRecord.addWidget(canvas)

    def update_waveform_realtime(self):
        with self.lock:
            framerate = 44100
            target_frequency = 500  # 目标频率(Hz)
            accumulated_frames = []  # 用于累积音频帧的列表

            while self.is_recording:
                if not self.audio_queue.empty():
                    data = self.audio_queue.get()
                    accumulated_frames.append(np.frombuffer(data, dtype='int16'))

                    if len(accumulated_frames) * len(data) >= framerate:  # 如果累积的音频数据达到或超过1秒
                        signal = np.concatenate(accumulated_frames)  # 合并所有音频帧
                        accumulated_frames = []  # 清空累积的帧

                        # 计算时间数组,确保其长度与 signal 相同
                        time_array = np.linspace(0., len(signal) / framerate, num=len(signal))

                        fft_spectrum = fft(signal)
                        magnitude = np.abs(fft_spectrum)
                        freq = np.fft.fftfreq(len(signal), 1.0 / framerate)

                        left_frequency = freq[:int(len(freq) / 2)]
                        left_magnitude = magnitude[:int(len(magnitude) / 2)]

                        max_magnitude = np.argmax(left_magnitude)
                        peak_freq = left_frequency[max_magnitude]
                        print('max_magnitude',max_magnitude,'peak_freq',peak_freq,'abs(peak_freq - target_frequency)',abs(peak_freq - target_frequency))

                        # 检查是否有接近目标频率的频率成分
                        #if abs(peak_freq - target_frequency) < 10:  # 可以根据需求调整频率容差
                        if abs(peak_freq - target_frequency) <= self.frequency_Tolerance:  # 可以根据需求调整频率容差
                            print(f"Detected target frequency: {peak_freq} Hz")
                            self.recordTestValues=peak_freq
                            self.is_recording = False
                            self.isRecordTestPass = True
                            self.label_9.setText('PASS')
                            self.label_9.setStyleSheet("color: green;")
                            self.update_waveform_signal.emit(time_array, signal)
                            if self.isTestCamera==True:
                                self.lbl_CurrentSwTest.setText("请开始测试摄相头..")
                            else:
                                self.lbl_CurrentSwTest.setText("麦克风测试通过!!")
                            break
                        else:
                            #print("No frequency component found near 500Hz")
                            self.update_waveform_signal.emit(time_array, signal)
                            time.sleep(1)  # 暂停一会儿

    def record_audio_realtime(self):
        self.label_12.setText("开始录音...")  # 添加的确认信息
        chunk = 1024
        format = pyaudio.paInt16
        channels = 1
        rate = 44100
        p = pyaudio.PyAudio()

        # 打开流
        stream = p.open(format=format, channels=channels, rate=rate, input=True, frames_per_buffer=chunk)

        self.is_recording = True
        frames = []  # 存储音频帧的列表
        while self.is_recording:
            data = stream.read(chunk)
            frames.append(data)  # 将音频帧添加到列表
            self.audio_queue.put(data)

        # 停止和关闭流
        stream.stop_stream()
        stream.close()
        p.terminate()

        if os.path.exists("recorded_audio.wav"):
            #删除文件
            os.remove("recorded_audio.wav")
        # 保存音频数据到文件
        output_filename = "recorded_audio.wav"
        try:
            wf = wave.open(output_filename, 'wb')
            wf.setnchannels(channels)
            wf.setsampwidth(p.get_sample_size(format))
            wf.setframerate(rate)
            wf.writeframes(b''.join(frames))
            wf.close()
            #print(f"录音完成,文件保存为: {output_filename}")
            self.label_12.setText(f"录音完成,文件保存为: {output_filename}")
        except Exception as e:
            #print(f"保存音频文件时出错: {e}")
            self.label_12.setText(f"保存音频文件时出错: {e}")

    def stop_recording(self):
        self.is_recording = False

    def start_realtime_audio_processing(self):
        if not self.is_recording:
            self.is_recording = True
            audio_thread = Thread(target=self.record_audio_realtime)
            audio_thread.start()
            waveform_thread = Thread(target=self.update_waveform_realtime)
            waveform_thread.start()

    # 新增方法:在主线程中更新音频波形
    def update_audio_waveform(self, audio_filename):
        """更新音频波形显示"""
        try:
            fig = self.display_audio_waveform(audio_filename)
            canvas = FigureCanvas(fig)
            self.QVB_LyRecord.addWidget(canvas)
            self.label_12.setText("波形图已生成")  # 更新提示信息
            QApplication.processEvents()
        except Exception as e:
            self.label_12.setText("波形图生成失败: " + str(e))  # 更新错误信息
            QApplication.processEvents()

    def display_audio_waveform(self, audio_filename="output.wav"):
        """显示音频波形"""
        with wave.open(audio_filename, 'r') as wf:
            signal = wf.readframes(-1)
            signal = np.frombuffer(signal, dtype='int16')
            framerate = wf.getframerate()
            time = np.linspace(0., len(signal) / framerate, num=len(signal))

            fig, ax = plt.subplots()
            ax.plot(time, signal)
            ax.set_xlabel('Time [s]')
            ax.set_ylabel('Amplitude')
            return fig

    def captureAndDecodeImage(self):
        ret, frame = self.capture.read()
        if ret:
            frame = cv2.flip(frame, 1)
            cv2.imwrite('captured_image.jpg', frame)
            decodedObjects = pyzbar.decode(frame)
            for obj in decodedObjects:
                data = obj.data.decode("utf-8")
                #print("Data", data)
                self.ShowLog("图像采集和解析中..", True)
                #if data == "test":
                if data==self.Image_Info:
                    self.cameraTestValues=data#解析图片的内容
                    self.captureTimer.stop()
                    self.isCameraTestPass=True
                    self.label_6.setText('PASS')
                    self.label_6.setStyleSheet("color: green;")
                    self.lbl_CurrentSwTest.setStyleSheet("background-color: rgb(85, 255, 127);color:green;")
                    if self.isTestRecord==True:
                        self.lbl_CurrentSwTest.setText("开始启动麦克风测试..")
                    else:
                        self.lbl_CurrentSwTest.setText("摄相头测试通过..")
                    break

    #判断最终测试结果
    def check_Test(self):
        if self.isTestCamera and self.isTestRecord:
            if self.isCameraTestPass and self.isRecordTestPass:
                self.UpdateJsonTestArgs(self.itemName,f'Carmera={self.cameraTestValues}|Record={self.recordTestValues}','PASS')#写入日志
                self.copy_file_to_shared_directory('captured_image.jpg', self.CameraImagePath,self.user, self.pwd,'.jpg')  # 上传照片文件
                self.copy_file_to_shared_directory('recorded_audio.wav', self.Recorded_AudioPath,self.user, self.pwd,'.wav')  # 上传音频文件
                sys.exit(0)
        elif self.isTestCamera:
            if self.isCameraTestPass:
                self.UpdateJsonTestArgs(self.itemName,f'Carmera={self.cameraTestValues}','PASS')  # 写入日志
                self.copy_file_to_shared_directory('captured_image.jpg', self.CameraImagePath,self.user, self.pwd,'.jpg')  # 上传照片文件
                sys.exit(0)
        elif self.isTestRecord:
            if self.isRecordTestPass:
                self.UpdateJsonTestArgs(self.itemName, f'Record={self.recordTestValues}', 'PASS')  # 写入日志
                self.copy_file_to_shared_directory('recorded_audio.wav', self.Recorded_AudioPath,self.user, self.pwd,'.wav')  # 上传音频文件
                sys.exit(0)

    # 更新测试参数json,itemName:项目名称,readValue:读取值,testResult:测试结果
    def UpdateJsonTestArgs(self, itemName, readValue, testResult):
        try:
            updateTestArgs = []  # 更新的测试参数
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    js['Read'] = readValue  # 读取的值
                    js['TestResult'] = testResult  # 测试结果
                    updateTestArgs.append(js)
                else:
                    updateTestArgs.append(js)
            with open("./Conf/TestArgs.json", "w") as write_file:
                json.dump(updateTestArgs, write_file)
            return True
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    #上传文件至服务器
    #source_path:拷贝的文件名称,shared_directory_path:服务器共享目录,username:用户名,password:密码
    def copy_file_to_shared_directory(self,source_path, shared_directory_path, username, password,extension):
        # 获取操作系统类型
        os_type = platform.system()
        # 如果是在Windows环境下,使用原始字符串处理路径
        if os_type == "Windows":
            shared_directory_path = shared_directory_path.replace('/', '\\')
            # 连接共享目录
            connect_command = f"net use {shared_directory_path} /user:{username} {password}"
            subprocess.run(connect_command, shell=True, check=True)
        elif os_type == "Linux" or os_type == "Darwin":
            # 对于Linux和MacOS,将Windows风格的共享路径转换为Unix风格的路径
            shared_directory_path = shared_directory_path.replace('\\', '/')
            if shared_directory_path.startswith('\\\\'):
                shared_directory_path = shared_directory_path.replace('\\\\', '/mnt/', 1)
            # 连接共享目录
            mount_command = f'mount {shared_directory_path} /mnt -o username="{username}",password="{password}"'
            subprocess.run(mount_command, shell=True, check=True)
        else:
            raise Exception("不支持的操作系统")

        # 使用os.path.join确保路径在不同操作系统中正确拼接
        #file_name = os.path.basename(f'{self.sn}{extension}')
        #destination_path = os.path.join(shared_directory_path, file_name)

        # 复制文件
        os.rename(source_path, f'{self.sn}{extension}')
        shutil.copy2(f'{self.sn}{extension}', '/mnt')
        #print(f"文件已成功复制到 {destination_path}")
        self.label_12.setText(f"{self.sn}{extension}'文件上传至服务器:{shared_directory_path} 成功!!")

    # 使用示例
    #source_file = '/path/to/your/source/file.txt'  # 本地源文件路径
    #shared_dir = '\\\\10.2.2.163\\Data\\LOG\\Microphone'  # Windows网络共享目录路径
    #copy_file_to_shared_directory(source_file, shared_dir)

    #读取json信息中MAC信息
    def ReadJsonSnInfo(self,fileName,KeyName):
        try:
            testArgs=self.ReadJsonInfo(fileName)
            for tss in testArgs:
                if KeyName in tss:
                    self.sn=tss[KeyName]
                    return True
        except Exception as e:
            self.ShowLog("Read OrderInfo.json ItemName:" + KeyName + " Info Err:" + str(e), False)

    def setupUi(self):
        self.setObjectName("CameraTestFrm")
        self.resize(1207, 895)
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("IMAGE/Subtract.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.setWindowIcon(icon)
        self.gridLayout = QtWidgets.QGridLayout(self)
        self.gridLayout.setObjectName("gridLayout")
        self.verticalLayout = QtWidgets.QVBoxLayout()
        self.verticalLayout.setObjectName("verticalLayout")
        self.horizontalLayout = QtWidgets.QHBoxLayout()
        self.horizontalLayout.setObjectName("horizontalLayout")
        self.verticalLayout_3 = QtWidgets.QVBoxLayout()
        self.verticalLayout_3.setObjectName("verticalLayout_3")
        self.horizontalLayout_3 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_3.setObjectName("horizontalLayout_3")
        self.label_3 = QtWidgets.QLabel(self)
        self.label_3.setText("")
        self.label_3.setPixmap(QtGui.QPixmap("IMAGE/logo.jpg"))
        self.label_3.setAlignment(QtCore.Qt.AlignCenter)
        self.label_3.setObjectName("label_3")
        self.horizontalLayout_3.addWidget(self.label_3)
        self.label_2 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.label_2.setFont(font)
        self.label_2.setStyleSheet("background-color: rgb(170, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label_2.setAlignment(QtCore.Qt.AlignCenter)
        self.label_2.setObjectName("label_2")
        self.horizontalLayout_3.addWidget(self.label_2)
        self.verticalLayout_3.addLayout(self.horizontalLayout_3)
        self.lbl_CurrentSwTest = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.lbl_CurrentSwTest.setFont(font)
        self.lbl_CurrentSwTest.setStyleSheet("background-color: rgb(85, 255, 127);")
        self.lbl_CurrentSwTest.setAlignment(QtCore.Qt.AlignCenter)
        self.lbl_CurrentSwTest.setObjectName("lbl_CurrentSwTest")
        self.verticalLayout_3.addWidget(self.lbl_CurrentSwTest)
        self.horizontalLayout.addLayout(self.verticalLayout_3)
        self.verticalLayout_4 = QtWidgets.QVBoxLayout()
        self.verticalLayout_4.setObjectName("verticalLayout_4")
        self.horizontalLayout_4 = QtWidgets.QHBoxLayout()
        self.horizontalLayout_4.setObjectName("horizontalLayout_4")
        self.verticalLayout_8 = QtWidgets.QVBoxLayout()
        self.verticalLayout_8.setObjectName("verticalLayout_8")
        self.label = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label.setFont(font)
        self.label.setStyleSheet("background-color: rgb(255, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label.setAlignment(QtCore.Qt.AlignCenter)
        self.label.setObjectName("label")
        self.verticalLayout_8.addWidget(self.label)
        self.label_5 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_5.setFont(font)
        self.label_5.setAlignment(QtCore.Qt.AlignCenter)
        self.label_5.setObjectName("label_5")
        self.verticalLayout_8.addWidget(self.label_5)
        self.label_4 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_4.setFont(font)
        self.label_4.setAlignment(QtCore.Qt.AlignCenter)
        self.label_4.setObjectName("label_4")
        self.verticalLayout_8.addWidget(self.label_4)
        self.horizontalLayout_4.addLayout(self.verticalLayout_8)
        self.verticalLayout_9 = QtWidgets.QVBoxLayout()
        self.verticalLayout_9.setObjectName("verticalLayout_9")
        self.label_7 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_7.setFont(font)
        self.label_7.setStyleSheet("background-color: rgb(255, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label_7.setAlignment(QtCore.Qt.AlignCenter)
        self.label_7.setObjectName("label_7")
        self.verticalLayout_9.addWidget(self.label_7)
        self.label_8 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_8.setFont(font)
        self.label_8.setAlignment(QtCore.Qt.AlignCenter)
        self.label_8.setObjectName("label_8")
        self.verticalLayout_9.addWidget(self.label_8)
        self.label_6 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_6.setFont(font)
        self.label_6.setAlignment(QtCore.Qt.AlignCenter)
        self.label_6.setObjectName("label_6")
        self.verticalLayout_9.addWidget(self.label_6)
        self.horizontalLayout_4.addLayout(self.verticalLayout_9)
        self.verticalLayout_7 = QtWidgets.QVBoxLayout()
        self.verticalLayout_7.setObjectName("verticalLayout_7")
        self.label_10 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_10.setFont(font)
        self.label_10.setStyleSheet("background-color: rgb(255, 170, 127);\n"
"color: rgb(255, 255, 255);")
        self.label_10.setAlignment(QtCore.Qt.AlignCenter)
        self.label_10.setObjectName("label_10")
        self.verticalLayout_7.addWidget(self.label_10)
        self.label_11 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_11.setFont(font)
        self.label_11.setAlignment(QtCore.Qt.AlignCenter)
        self.label_11.setObjectName("label_11")
        self.verticalLayout_7.addWidget(self.label_11)
        self.label_9 = QtWidgets.QLabel(self)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_9.setFont(font)
        self.label_9.setAlignment(QtCore.Qt.AlignCenter)
        self.label_9.setObjectName("label_9")
        self.verticalLayout_7.addWidget(self.label_9)
        self.horizontalLayout_4.addLayout(self.verticalLayout_7)
        self.verticalLayout_4.addLayout(self.horizontalLayout_4)
        self.horizontalLayout.addLayout(self.verticalLayout_4)
        self.verticalLayout.addLayout(self.horizontalLayout)
        self.horizontalLayout_2 = QtWidgets.QHBoxLayout()
        #self.horizontalLayout_2 = QtWidgets.QVBoxLayout()
        self.horizontalLayout_2.setObjectName("horizontalLayout_2")
        self.QVB_LyCamera = QtWidgets.QVBoxLayout()
        self.QVB_LyCamera.setObjectName("QVB_LyCamera")
        self.horizontalLayout_2.addLayout(self.QVB_LyCamera, 1)  # 指定比例为1

        # 创建显示摄像头画面的 QLabel
        self.image_label = QLabel(self)
        self.QVB_LyCamera.addWidget(self.image_label)
        self.QVB_LyRecord = QtWidgets.QVBoxLayout()
        self.QVB_LyRecord.setObjectName("QVB_LyRecord")
        self.horizontalLayout_2.addLayout(self.QVB_LyRecord, 1)  # 指定比例为1
        self.verticalLayout.addLayout(self.horizontalLayout_2)
        self.verticalLayout_2 = QtWidgets.QVBoxLayout()
        self.verticalLayout_2.setObjectName("verticalLayout_2")
        self.groupBox = QtWidgets.QGroupBox(self)
        font = QtGui.QFont()
        font.setPointSize(13)
        font.setBold(True)
        font.setWeight(75)
        self.groupBox.setFont(font)
        self.groupBox.setStyleSheet("color: rgb(255, 255, 255);\n"
"background-color: rgb(170, 170, 127);")
        self.groupBox.setAlignment(QtCore.Qt.AlignCenter)
        self.groupBox.setObjectName("groupBox")
        self.gridLayout_2 = QtWidgets.QGridLayout(self.groupBox)
        self.gridLayout_2.setObjectName("gridLayout_2")
        self.label_12 = QtWidgets.QLabel(self.groupBox)
        font = QtGui.QFont()
        font.setPointSize(12)
        self.label_12.setFont(font)
        self.label_12.setStyleSheet("background-color: rgb(0, 0, 0);\n"
"color: rgb(255, 255, 127);")
        self.label_12.setAlignment(QtCore.Qt.AlignCenter)
        self.label_12.setObjectName("label_12")
        self.gridLayout_2.addWidget(self.label_12, 0, 0, 1, 1)
        self.verticalLayout_2.addWidget(self.groupBox)
        self.verticalLayout.addLayout(self.verticalLayout_2)
        self.gridLayout.addLayout(self.verticalLayout, 0, 0, 1, 1)


        self.retranslateUi()
        QtCore.QMetaObject.connectSlotsByName(self)
        self.setWindowFlags(QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)  # 只显示最小化按钮和关闭按钮

    def retranslateUi(self):
        _translate = QtCore.QCoreApplication.translate
        self.setWindowTitle(_translate("CameraTestFrm", "CameraTestFrm"))
        self.label_2.setText(_translate("CameraTestFrm", "控制过程"))
        self.lbl_CurrentSwTest.setText(_translate("CameraTestFrm", "Wait.."))
        self.label.setText(_translate("CameraTestFrm", "测试项目名称"))
        self.label_5.setText(_translate("CameraTestFrm", "配置参数"))
        self.label_4.setText(_translate("CameraTestFrm", "测试结果"))
        self.label_7.setText(_translate("CameraTestFrm", "摄相头"))
        self.label_8.setText(_translate("CameraTestFrm", "N/A"))
        self.label_6.setText(_translate("CameraTestFrm", "N/A"))
        self.label_10.setText(_translate("CameraTestFrm", "麦克风"))
        self.label_11.setText(_translate("CameraTestFrm", "N/A"))
        self.label_9.setText(_translate("CameraTestFrm", "N/A"))
        self.groupBox.setTitle(_translate("CameraTestFrm", "人机交互提示"))
        self.label_12.setText(_translate("CameraTestFrm", "摄相头测试,请将测试治具,二维条码字样对准摄相头!!"))

    # 读取json信息
    def ReadJsonInfo(self, fileName):
        try:
            if os.path.exists(fileName):
                f = open(fileName, 'r', encoding='utf-8')
            return json.loads(f.read())
        except Exception as e:
            self.ShowLog("Read " + fileName + " Err:" + str(e), False)
            sys.exit(1)

    # 读取项目参数信息,itemName:项目名称
    def ReadJsonTestArgs(self, itemName):
        try:
            self.testArgs = self.ReadJsonInfo('./Conf/TestArgs.json')
            for js in self.testArgs:
                if itemName in js['ItemName']:
                    self.testStandardArgs = js['Standard']
                    return True
            self.ShowLog('Read TestArgs.json ItemName:' + itemName + ' Info Is Empty!!', False)
            sys.exit(1)
        except Exception as e:
            self.ShowLog("Read TestArgs.json ItemName:" + itemName + " Info Err:" + str(e), False)
            sys.exit(1)

    # 打印的信息
    def ShowLog(self, log, isPass):
        try:
            if isPass == True:
                self.lbl_CurrentSwTest.setStyleSheet("background-color: rgb(85, 255, 127);color:green;")
                self.logger.info(str(log))
                self.lbl_CurrentSwTest.setText("TEST PASS")
            else:
                self.lbl_CurrentSwTest.setStyleSheet("background-color: rgb(85, 255, 127);color: red;")
                self.logger.error(str(log))
                self.lbl_CurrentSwTest.setText(log)
        except Exception as e:
            print("\033[1;31m" + str(e) + " \033[0m")
            sys.exit(1)

    # 启动线重脚本
    def TestThread(self):
        pass
        # self.t_autoplay=Thread(target=self.Test)
        # self.t_autoplay.start()

    #手动关闭窗口
    def closeEvent(self, event):
        # 告知线程停止运行
        self.running = False
        # 等待线程结束
        if self.microphone_test_thread is not None:
            self.microphone_test_thread.join()
        # 其他关闭操作
        if self.capture.isOpened():
            self.capture.release()
        event.accept()
        sys.exit(1)

    # 定义一个函数使得函数窗口居中显示
    def Center(self):
        # 获取屏幕尺寸
        screen_geometry = app.desktop().availableGeometry()
        # 计算窗口居中位置
        x = (screen_geometry.width() - self.width()) // 2
        y = (screen_geometry.height() - self.height()) // 2
        # 设置窗口位置
        self.move(x, y)

if __name__=='__main__':
    app=QApplication(sys.argv)
    win=Ui_CameraTestFrm()
    win.Center()  # 居中
    win.show()
    #win.start_realtime_audio_processing()  # 启动实时音频处理
    sys.exit(app.exec_())
相关推荐
alphaTao1 小时前
LeetCode 每日一题 2024/10/28-2024/11/3
python·算法·leetcode
Liquor14191 小时前
JavaScript知识点梳理及案例实践
开发语言·前端·javascript·python·css3·html5·js
张小生1802 小时前
《YOLO 目标检测》—— YOLO v4 详细介绍
人工智能·python·yolo
无敌最俊朗@2 小时前
unity3d————球形插值知识点
开发语言·学习·unity·c#·游戏引擎
凡人的AI工具箱3 小时前
15分钟学 Go 第 37 天:综合复习与小项目
开发语言·后端·算法·golang
hummhumm4 小时前
Oracle 第22章:数据仓库与OLAP
java·javascript·后端·python·sql·mysql·database
归仁6 小时前
wvp 推拉转级联时频繁出现流无法观看的解决办法
linux·服务器·python·音视频
Trouvaille ~6 小时前
【C++篇】在秩序与混沌的交响乐中: STL之map容器的哲学探寻
开发语言·数据结构·c++·算法·迭代器模式·stl·map
开心工作室_kaic6 小时前
ssm042在线云音乐系统的设计与实现+jsp(论文+源码)_kaic
java·开发语言·php
334554328 小时前
element表格双击修改时间
开发语言·前端·javascript