在 SystemUI 的 Statusbar 中 添加 ethernet status icon

本文详细解析了Android系统中状态栏网络图标显示原理及其实现过程,特别是针对Ethernet状态图标的添加与更新机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于源处网站被360安全警告提示,有广告或木码,所以就不贴出源处了,请谅解

涉及的源代码主要是 frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkController.java


这个代码里 集成了 3G, wifi, bluetooth, wimax 还有电池量 等信号的 状态显示功能,所以ethernet status icon也添加到这里来了。

1. NetworkController 类:

/** * Construct this controller object and register for updates. */ 
public NetworkController(Context context) {
    mContext = context; 
    final Resources res = context.getResources(); 
    ConnectivityManager cm = (ConnectivityManager)mContext.getSystemService( Context.CONNECTIVITY_SERVICE); 
    //mHasMobileDataFeature = cm.isNetworkSupported(ConnectivityManager.TYPE_MOBILE); //这里把mobile注销了 
    mEthernetConnected = cm.isNetworkSupported(ConnectivityManager.TYPE_ETHERNET); //添加ethernet功能 
    mShowPhoneRSSIForData = res.getBoolean(R.bool.config_showPhoneRSSIForData); 
    mShowAtLeastThreeGees = res.getBoolean(R.bool.config_showMin3G); 
    mAlwaysShowCdmaRssi = res.getBoolean( com.android.internal.R.bool.config_alwaysUseCdmaRssi); 
    // set up the default wifi icon, used when no radios have ever appeared 
    updateWifiIcons(); 
    pdateWimaxIcons(); 
    // telephony 
    mPhone = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE); 
    mPhone.listen(mPhoneStateListener, PhoneStateListener.LISTEN_SERVICE_STATE
                                          | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS 
                                          | PhoneStateListener.LISTEN_CALL_STATE
                                          | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE
                                          | PhoneStateListener.LISTEN_DATA_ACTIVITY); 
    mHspaDataDistinguishable = mContext.getResources().getBoolean( R.bool.config_hspa_data_distinguishable); 
    mNetworkNameSeparator = mContext.getString(R.string.status_bar_network_name_separator); 
    mNetworkNameDefault = mContext.getString( com.android.internal.R.string.lockscreen_carrier_default); 
    mNetworkName = mNetworkNameDefault; 
    // wifi 
    mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); 
    Handler handler = new WifiHandler(); 
    mWifiChannel = new AsyncChannel(); 
    Messenger wifiMessenger = mWifiManager.getMessenger(); 
    if (wifiMessenger != null) {
        mWifiChannel.connect(mContext, handler, wifiMessenger); 
    }
    // broadcasts 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction(WifiManager.RSSI_CHANGED_ACTION); 
    filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); 
    filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); 
    filter.addAction(EthernetManager.ETHERNET_STATE_CHANGED_ACTION); 
    filter.addAction(TelephonyIntents.ACTION_SIM_STATE_CHANGED); 
    filter.addAction(Telephony.Intents.SPN_STRINGS_UPDATED_ACTION); 
    filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION); 
    filter.addAction(ConnectivityManager.INET_CONDITION_ACTION); 
    filter.addAction(Intent.ACTION_CONFIGURATION_CHANGED); 
    filter.addAction(Intent.ACTION_AIRPLANE_MODE_CHANGED); 
    mWimaxSupported = mContext.getResources().getBoolean( com.android.internal.R.bool.config_wimaxEnabled); 
    if(mWimaxSupported) { 
        filter.addAction(WimaxManagerConstants.WIMAX_NETWORK_STATE_CHANGED_ACTION); 
        filter.addAction(WimaxManagerConstants.SIGNAL_LEVEL_CHANGED_ACTION); 
        filter.addAction(WimaxManagerConstants.NET_4G_STATE_CHANGED_ACTION);
    } 
    context.registerReceiver(this, filter); 
    // AIRPLANE_MODE_CHANGED is sent at boot; we've probably already missed it 
    updateAirplaneMode(); 
    // yuck 
    mBatteryStats = BatteryStatsService.getService(); 
}
2. 这个类的主要运行函数是 onReceive():

    @Override
    public void onReceive(Context context, Intent intent) {
        final String action = intent.getAction();
        if (action.equals(WifiManager.RSSI_CHANGED_ACTION)
                || action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)
                || action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
            updateWifiState(intent);
            refreshViews();  //刷新显示栏
        } else if (action.equals(TelephonyIntents.ACTION_SIM_STATE_CHANGED)) {
            updateSimState(intent);
            updateDataIcon();
            refreshViews();
        } else if (action.equals(Telephony.Intents.SPN_STRINGS_UPDATED_ACTION)) {
            updateNetworkName(intent.getBooleanExtra(Telephony.Intents.EXTRA_SHOW_SPN, false),
                        intent.getStringExtra(Telephony.Intents.EXTRA_SPN),
                        intent.getBooleanExtra(Telephony.Intents.EXTRA_SHOW_PLMN, false),
                        intent.getStringExtra(Telephony.Intents.EXTRA_PLMN));
            refreshViews();
        } else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION) ||
                 action.equals(ConnectivityManager.INET_CONDITION_ACTION)) {
            updateConnectivity(intent);  //这个是更新链接状态
            refreshViews();
        } else if (action.equals(Intent.ACTION_CONFIGURATION_CHANGED)) {
            refreshViews();
        } else if (action.equals(Intent.ACTION_AIRPLANE_MODE_CHANGED)) {
            updateAirplaneMode();
            refreshViews();
        } else if (action.equals(EthernetManager.ETHERNET_STATE_CHANGED_ACTION)) {
            updateEth(intent);  //更新网络功能
            refreshViews();
        } else if (action.equals(WimaxManagerConstants.NET_4G_STATE_CHANGED_ACTION) ||
                action.equals(WimaxManagerConstants.SIGNAL_LEVEL_CHANGED_ACTION) ||
                action.equals(WimaxManagerConstants.WIMAX_NETWORK_STATE_CHANGED_ACTION)) {
            updateWimaxState(intent);
            refreshViews();
        }
    }
3. refreshViews() ,连接状态更新后,要刷新显示内容,这个函数有点长,缩略一下:

// ===== Update the views =======================================================
void refreshViews() {
    Context context = mContext; 
    int combinedSignalIconId = 0; 
    int combinedActivityIconId = 0; 
    String combinedLabel = ""; 
    String wifiLabel = ""; 
    String mobileLabel = ""; 
    int N;
    .............................
    if (mEthernetConnected) {
        switch (mEthernetActivity) { 
        //根据mEthernetActiviy 来判断不同的状态,进而显示不同图片 
        case EthernetStateTracker.EVENT_HW_CONNECTED: 
        case EthernetStateTracker.EVENT_INTERFACE_CONFIGURATION_SUCCEEDED: 
            mEthernetIconId = sEthImages[0]; 
            break; 
        case EthernetStateTracker.EVENT_HW_DISCONNECTED: 
        case EthernetStateTracker.EVENT_INTERFACE_CONFIGURATION_FAILED: 
            mEthernetIconId = sEthImages[1]; 
            break; 
        default: 
            mEthernetIconId = sEthImages[2]; 
        } 
        combinedActivityIconId = mEthernetIconId; 
        combinedLabel = ""; 
        combinedSignalIconId = mEthernetIconId; 
        mContentDescriptionCombinedSignal = ""; 
    }
    .............................
    if (DEBUG) {
            Slog.d(TAG, "refreshViews connected={"
                    + (mWifiConnected?" wifi":"")
                    + (mDataConnected?" data":"")
                    + " } level="
                    + ((mSignalStrength == null)?"??":Integer.toString(mSignalStrength.getLevel()))
                    + " combinedSignalIconId=0x"
                    + Integer.toHexString(combinedSignalIconId)
                    + "/" + getResourceName(combinedSignalIconId)
                    + " combinedActivityIconId=0x" + Integer.toHexString(combinedActivityIconId)
                    + " mAirplaneMode=" + mAirplaneMode
                    + " mDataActivity=" + mDataActivity
                    + " mPhoneSignalIconId=0x" + Integer.toHexString(mPhoneSignalIconId)
                    + " mDataDirectionIconId=0x" + Integer.toHexString(mDataDirectionIconId)
                    + " mDataSignalIconId=0x" + Integer.toHexString(mDataSignalIconId)
                    + " mDataTypeIconId=0x" + Integer.toHexString(mDataTypeIconId)
                    + " mEthernetIconId=0x" + Integer.toHexString(mEthernetIconId)
                    + " mWifiIconId=0x" + Integer.toHexString(mWifiIconId)
                    + " mBluetoothTetherIconId=0x" + Integer.toHexString(mBluetoothTetherIconId)
           );
    } 
    if (mLastPhoneSignalIconId != mPhoneSignalIconId 
            || mLastDataDirectionOverlayIconId != combinedActivityIconId 
            || mLastWifiIconId != mWifiIconId 
            || mLastWimaxIconId != mWimaxIconId 
            || mLastEthernetIconId != mEthernetIconId 
            || mLastDataTypeIconId != mDataTypeIconId) {
                // NB: the mLast*s will be updated later 
        for (SignalCluster cluster : mSignalClusters) {
            refreshSignalCluster(cluster); //刷新信号簇
        }
    }
    .............................
    // the ethernet icon on statusbar 
    if (mLastEthernetIconId != mEthernetIconId){
        mLastEthernetIconId = mEthernetIconId; 
        N = mEthernetIconViews.size();
        for (int i=0; i<N; i++) {
            final ImageView v = mEthernetIconViews.get(i);
            if (mEthernetIconId == 0) {
                v.setVisibility(View.GONE);
            } else { 
                v.setVisibility(View.VISIBLE); //设为可见
                v.setImageResource(mEthernetIconId);//显示图片内容
                v.setContentDescription(mContentDescriptionEthernet);//内容描述
            }
        }
    } 
    // the combinedLabel in the notification panel 
    if (!mLastCombinedLabel.equals(combinedLabel)) {
        mLastCombinedLabel = combinedLabel; 
        N = mCombinedLabelViews.size(); 
        for (int i=0; i<N; i++) {
            TextView v = mCombinedLabelViews.get(i);
            v.setText(combinedLabel);
        }
    }
    // wifi label
    N = mWifiLabelViews.size();
    for (int i=0; i<N; i++) {
        TextView v = mWifiLabelViews.get(i);
        if ("".equals(wifiLabel)) {
            v.setVisibility(View.GONE);
        } else {
            v.setVisibility(View.VISIBLE);
            v.setText(wifiLabel);
        }
    } 
    // mobile label 
    N = mMobileLabelViews.size(); 
    for (int i=0; i<N; i++) { 
        TextView v = mMobileLabelViews.get(i); 
        if ("".equals(mobileLabel)) {
            v.setVisibility(View.GONE);
        } else {
            v.setVisibility(View.VISIBLE);
            v.setText(mobileLabel);
        }
    }
}
4.  OnReceive() 得到 EthernetManager.ETHERNET_STATE_CHANGED_ACTION 信号后,会运行 updateEth(intent),来更新Ethernet状态:
    private final void updateEth(Intent intent) {
        final int event = intent.getIntExtra(EthernetManager.EXTRA_ETHERNET_STATE, EthernetManager.ETHERNET_STATE_UNKNOWN);
        switch (event) {
            case EthernetStateTracker.EVENT_HW_CONNECTED:
            case EthernetStateTracker.EVENT_INTERFACE_CONFIGURATION_SUCCEEDED:
                mEthernetIconId = sEthImages[0];
                break;
            case EthernetStateTracker.EVENT_HW_DISCONNECTED:
            case EthernetStateTracker.EVENT_INTERFACE_CONFIGURATION_FAILED:
                mEthernetIconId = sEthImages[1];
                return;
            default:
                mEthernetIconId = sEthImages[2];
        }
    }
5. updateConnectivity(Intent intent), onReceive() 得到 ConnectivityManager.CONNECTIVITY_ACTION 信号后,会运行这个函数:
    // ===== Full or limited Internet connectivity ==================================

    private void updateConnectivity(Intent intent) {
        if (CHATTY) {
            Slog.d(TAG, "updateConnectivity: intent=" + intent);
        }

        NetworkInfo info = (NetworkInfo)(intent.getParcelableExtra(
                ConnectivityManager.EXTRA_NETWORK_INFO));
        int connectionStatus = intent.getIntExtra(ConnectivityManager.EXTRA_INET_CONDITION, 0);

        if (info.isConnected()) {  //通过 ethernetinfo 来判断 ethernet 连接状态
            mEthernetActivity = EthernetStateTracker.EVENT_HW_CONNECTED;
        } else if (!info.isConnected() && info.isConnectedOrConnecting()) {
            mEthernetActivity = EthernetStateTracker.EVENT_DHCP_START;
        } else {
            mEthernetActivity = EthernetStateTracker.EVENT_HW_DISCONNECTED;
        }
        Slog.d(TAG, "updateConnectivity: mEthernetActivity = " + mEthernetActivity);

        if (CHATTY) {
            Slog.d(TAG, "updateConnectivity: networkInfo=" + info);
            Slog.d(TAG, "updateConnectivity: connectionStatus=" + connectionStatus);
        }
        mInetCondition = (connectionStatus > INET_CONDITION_THRESHOLD ? 1 : 0);

        if (info != null && info.getType() == ConnectivityManager.TYPE_BLUETOOTH) {
            mBluetoothTethered = info.isConnected();
        } else {
            mBluetoothTethered = false;
        }

        // We want to update all the icons, all at once, for any condition change
        updateDataNetType();
        updateWimaxIcons();
        updateDataIcon();
        updateEthernetIcons(); //更新etherent Icon
        updateTelephonySignalStrength();
        updateWifiIcons();
    }
updateEthernetIcons():
    private void updateEthernetIcons() {
        if (mEthernetConnected) {
            mEthernetIconId = sEthImages[0];
        } else {
            mEthernetIconId = sEthImages[1];
        }
    }




# -*- coding: utf-8 -*- import sys import os import cv2 import numpy as np import time from PyQt5.QtWidgets import ( QApplication, QMainWindow, QPushButton, QWidget, QVBoxLayout, QHBoxLayout, QMessageBox, QLabel, QFileDialog, QToolBar, QComboBox, QStatusBar, QGroupBox, QSlider, QDockWidget, QProgressDialog, QLineEdit, QRadioButton, QGridLayout, QSpinBox ) from PyQt5.QtCore import QRect, Qt, QSettings, QThread, pyqtSignal from CamOperation_class import CameraOperation sys.path.append("D:\\海康\\MVS\\Development\\Samples\\Python\\BasicDemo") import ctypes from ctypes import cast, POINTER from datetime import datetime import logging import socket import serial import skimage import platform from CameraConstants import * import threading import time import sys class ManagedThread(threading.Thread): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self._stop_event = threading.Event() # 设置为非守护线程 self.daemon = False def stop(self): """安全停止线程""" self._stop_event.set() def should_stop(self): """检查是否应该停止""" return self._stop_event.is_set() def worker(): """线程工作函数""" try: while not threading.current_thread().should_stop(): # 模拟工作 time.sleep(1) # 安全输出 sys.stdout.write("Working...\n") except Exception as e: # 避免在关闭时使用stderr pass def main(): # 创建并启动线程 threads = [] for _ in range(3): t = ManagedThread(target=worker) t.start() threads.append(t) try: # 主程序逻辑 time.sleep(5) finally: # 安全停止所有线程 for t in threads: t.stop() for t in threads: t.join(timeout=2.0) # 设置超时避免无限等待 # 确保所有输出完成 sys.stdout.flush() sys.stderr.flush() # 在导入部分添加 from CameraParams_header import ( MV_GIGE_DEVICE, MV_USB_DEVICE, MV_GENTL_CAMERALINK_DEVICE, MV_GENTL_CXP_DEVICE, MV_GENTL_XOF_DEVICE ) # ===== 路径修复 ===== def fix_sdk_path(): """修复海康SDK的加载路径""" if getattr(sys, 'frozen', False): # 打包模式 base_path = sys._MEIPASS mvimport_path = os.path.join(base_path, "MvImport") if mvimport_path not in sys.path: sys.path.insert(0, mvimport_path) if sys.platform == 'win32': os.environ['PATH'] = base_path + os.pathsep + os.environ['PATH'] try: ctypes.WinDLL(os.path.join(base_path, "MvCamCtrldll.dll")) except OSError as e: print(f"核心DLL加载失败: {e}") sys.exit(1) else: # 开发模式 sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) # 立即执行路径修复 fix_sdk_path() # ===== 正确导入SDK模块 ===== try: from MvImport.MvCameraControl_class import MvCamera print("成功导入MvCamera类") from CameraParams_header import * from MvErrorDefine_const import * except ImportError as e: print(f"SDK导入失败: {e}") sys.exit(1) # 配置日志系统 logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler("cloth_inspection_debug.log"), logging.StreamHandler() ] ) logging.info("布料印花检测系统启动") # 全局变量 current_sample_path = "" detection_history = [] isGrabbing = False isOpen = False obj_cam_operation = None frame_monitor_thread = None sensor_monitor_thread = None sensor_controller = None MV_OK = 0 MV_E_CALLORDER = -2147483647 # ==================== 传感器通讯模块 ==================== class SensorController: def __init__(self): self.connected = False self.running = False self.connection = None def connect(self, config): try: if config['type'] == 'serial': self.connection = serial.Serial( port=config['port'], baudrate=config['baudrate'], timeout=config.get('timeout', 1.0) ) else: self.connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.connection.connect((config['ip'], config['port'])) self.connection.settimeout(config.get('timeout', 1.0)) self.connected = True self.running = True logging.info(f"传感器连接成功: {config}") return True except Exception as e: logging.error(f"传感器连接失败: {str(e)}") return False def disconnect(self): if self.connection: try: self.connection.close() except: pass self.connection = None self.connected = False self.running = False logging.info("传感器已断开") def read_data(self): if not self.connected: return None return { 'tension': np.random.uniform(10.0, 20.0), 'speed': np.random.uniform(1.0, 5.0), 'temperature': np.random.uniform(20.0, 30.0), 'humidity': np.random.uniform(40.0, 60.0) } def wait_for_material(self, delay_seconds=0): if not self.connected: logging.warning("未连接传感器,跳过等待") return False logging.info(f"等待布料到达,延迟 {delay_seconds} 秒") start_time = time.time() while time.time() - start_time < delay_seconds: QThread.msleep(100) if not self.running: return False logging.info("布料已到位,准备拍摄") return True class SensorMonitorThread(QThread): data_updated = pyqtSignal(dict) def __init__(self, sensor_controller): super().__init__() self.sensor_controller = sensor_controller self.running = True def run(self): while self.running: if self.sensor_controller and self.sensor_controller.connected: try: data = self.sensor_controller.read_data() if data: self.data_updated.emit(data) except Exception as e: logging.error(f"传感器数据读取错误: {str(e)}") QThread.msleep(500) def stop(self): self.running = False self.wait(2000) def wait_for_material(self, delay_seconds): return self.sensor_controller.wait_for_material(delay_seconds) # ==================== 相机帧监控线程 ==================== class FrameMonitorThread(QThread): frame_status = pyqtSignal(str) # 用于发送状态消息的信号 def __init__(self, cam_operation): super().__init__() self.cam_operation = cam_operation self.running = True self.frame_count = 0 self.last_time = time.time() def run(self): """监控相机帧状态的主循环""" while self.running: try: if self.cam_operation and self.cam_operation.is_grabbing: # 获取帧统计信息 frame_info = self.get_frame_info() if frame_info: fps = frame_info.get('fps', 0) dropped = frame_info.get('dropped', 0) status = f"FPS: {fps:.1f} | 丢帧: {dropped}" self.frame_status.emit(status) else: self.frame_status.emit("取流中...") else: self.frame_status.emit("相机未取流") except Exception as e: self.frame_status.emit(f"监控错误: {str(e)}") # 每500ms检查一次 QThread.msleep(500) def stop(self): """停止监控线程""" self.running = False self.wait(1000) # 等待线程结束 def calculate_fps(self): """计算当前帧率""" current_time = time.time() elapsed = current_time - self.last_time if elapsed > 0: fps = self.frame_count / elapsed self.frame_count = 0 self.last_time = current_time return fps return 0 def get_frame_info(self): """获取帧信息""" try: # 更新帧计数 self.frame_count += 1 # 返回帧信息 return { 'fps': self.calculate_fps(), 'dropped': 0 # 实际应用中需要从相机获取真实丢帧数 } except Exception as e: logging.error(f"获取帧信息失败: {str(e)}") return None # ==================== 优化后的检测算法 ==================== def enhanced_check_print_quality(sample_image_path, test_image, threshold=0.05, sensor_data=None): if sensor_data: speed_factor = min(1.0 + sensor_data['speed'] * 0.1, 1.5) env_factor = 1.0 + abs(sensor_data['temperature'] - 25) * 0.01 + abs(sensor_data['humidity'] - 50) * 0.005 adjusted_threshold = threshold * speed_factor * env_factor logging.info(f"根据传感器数据调整阈值: 原始={threshold:.4f}, 调整后={adjusted_threshold:.4f}") else: adjusted_threshold = threshold try: sample_img_data = np.fromfile(sample_image_path, dtype=np.uint8) sample_image = cv2.imdecode(sample_img_data, cv2.IMREAD_GRAYSCALE) if sample_image is None: logging.error(f"无法解码样本图像: {sample_image_path}") return None, None, None except Exception as e: logging.exception(f"样本图像读取异常: {str(e)}") return None, None, None if len(test_image.shape) == 3: test_image_gray = cv2.cvtColor(test_image, cv2.COLOR_BGR2GRAY) else: test_image_gray = test_image.copy() sample_image = cv2.GaussianBlur(sample_image, (5, 5), 0) test_image_gray = cv2.GaussianBlur(test_image_gray, (5, 5), 0) try: orb = cv2.ORB_create(nfeatures=200) keypoints1, descriptors1 = orb.detectAndCompute(sample_image, None) keypoints2, descriptors2 = orb.detectAndCompute(test_image_gray, None) if descriptors1 is None or descriptors2 is None: logging.warning("无法提取特征描述符,跳过配准") aligned_sample = sample_image else: bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True) matches = bf.match(descriptors1, descriptors2) matches = sorted(matches, key=lambda x: x.distance) if len(matches) > 10: src_pts = np.float32([keypoints1[m.queryIdx].pt for m in matches]).reshape(-1, 1, 2) dst_pts = np.float32([keypoints2[m.trainIdx].pt for m in matches]).reshape(-1, 1, 2) H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0) if H is not None: aligned_sample = cv2.warpPerspective( sample_image, H, (test_image_gray.shape[1], test_image_gray.shape[0]) ) logging.info("图像配准成功,使用配准后样本") else: aligned_sample = sample_image logging.warning("无法计算单应性矩阵,使用原始样本") else: aligned_sample = sample_image logging.warning("特征点匹配不足,跳过图像配准") except Exception as e: logging.error(f"图像配准失败: {str(e)}") aligned_sample = sample_image try: if aligned_sample.shape != test_image_gray.shape: test_image_gray = cv2.resize(test_image_gray, (aligned_sample.shape[1], aligned_sample.shape[0])) except Exception as e: logging.error(f"图像调整大小失败: {str(e)}") return None, None, None try: from skimage.metrics import structural_similarity as compare_ssim ssim_score, ssim_diff = compare_ssim( aligned_sample, test_image_gray, full=True, gaussian_weights=True, data_range=255 ) except ImportError: from skimage.measure import compare_ssim ssim_score, ssim_diff = compare_ssim( aligned_sample, test_image_gray, full=True, gaussian_weights=True ) except Exception as e: logging.error(f"SSIM计算失败: {str(e)}") abs_diff = cv2.absdiff(aligned_sample, test_image_gray) ssim_diff = abs_diff.astype(np.float32) / 255.0 ssim_score = 1.0 - np.mean(ssim_diff) ssim_diff = (1 - ssim_diff) * 255 abs_diff = cv2.absdiff(aligned_sample, test_image_gray) combined_diff = cv2.addWeighted(ssim_diff.astype(np.uint8), 0.7, abs_diff, 0.3, 0) _, thresholded = cv2.threshold(combined_diff, 30, 255, cv2.THRESH_BINARY) kernel = np.ones((3, 3), np.uint8) thresholded = cv2.morphologyEx(thresholded, cv2.MORPH_OPEN, kernel) thresholded = cv2.morphologyEx(thresholded, cv2.MORPH_CLOSE, kernel) diff_pixels = np.count_nonzero(thresholded) total_pixels = aligned_sample.size diff_ratio = diff_pixels / total_pixels is_qualified = diff_ratio <= adjusted_threshold marked_image = cv2.cvtColor(test_image_gray, cv2.COLOR_GRAY2BGR) marked_image[thresholded == 255] = [0, 0, 255] labels = skimage.measure.label(thresholded) properties = skimage.measure.regionprops(labels) for prop in properties: if prop.area > 50: y, x = prop.centroid cv2.putText(marked_image, f"Defect", (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 255), 1) return is_qualified, diff_ratio, marked_image # ==================== 传感器控制的质量检测流程 ==================== def sensor_controlled_check(): global isGrabbing, obj_cam_operation, current_sample_path, detection_history, sensor_controller logging.info("质量检测启动") sensor_data = None if sensor_controller and sensor_controller.connected: sensor_data = sensor_controller.read_data() if not sensor_data: QMessageBox.warning(mainWindow, "传感器警告", "无法读取传感器数据,将使用默认参数", QMessageBox.Ok) else: logging.info("未连接传感器,使用默认参数检测") check_print_with_sensor(sensor_data) def check_print_with_sensor(sensor_data=None): global isGrabbing, obj_cam_operation, current_sample_path, detection_history logging.info("检测印花质量按钮按下") if not isGrabbing: QMessageBox.warning(mainWindow, "错误", "请先开始取流并捕获图像!", QMessageBox.Ok) return if not obj_cam_operation: QMessageBox.warning(mainWindow, "错误", "相机未正确初始化!", QMessageBox.Ok) return if not current_sample_path or not os.path.exists(current_sample_path): QMessageBox.warning(mainWindow, "错误", "请先设置有效的标准样本图像!", QMessageBox.Ok) return progress = QProgressDialog("正在检测...", "取消", 0, 100, mainWindow) progress.setWindowModality(Qt.WindowModal) progress.setValue(10) try: test_image = obj_cam_operation.get_current_frame() progress.setValue(30) if test_image is None: QMessageBox.warning(mainWindow, "错误", "无法获取当前帧图像!", QMessageBox.Ok) return diff_threshold = mainWindow.sliderDiffThreshold.value() / 100.0 logging.info(f"使用差异度阈值: {diff_threshold}") progress.setValue(50) is_qualified, diff_ratio, marked_image = enhanced_check_print_quality( current_sample_path, test_image, threshold=diff_threshold, sensor_data=sensor_data ) progress.setValue(70) if is_qualified is None: QMessageBox.critical(mainWindow, "检测错误", "检测失败,请检查日志", QMessageBox.Ok) return logging.info(f"检测结果: 合格={is_qualified}, 差异={diff_ratio}") progress.setValue(90) update_diff_display(diff_ratio, is_qualified) result_text = f"印花是否合格: {'合格' if is_qualified else '不合格'}\n差异占比: {diff_ratio*100:.2f}%\n阈值: {diff_threshold*100:.2f}%" QMessageBox.information(mainWindow, "检测结果", result_text, QMessageBox.Ok) if marked_image is not None: cv2.imshow("缺陷标记结果", marked_image) cv2.waitKey(0) cv2.destroyAllWindows() detection_result = { 'timestamp': datetime.now(), 'qualified': is_qualified, 'diff_ratio': diff_ratio, 'threshold': diff_threshold, 'sensor_data': sensor_data if sensor_data else {} } detection_history.append(detection_result) update_history_display() progress.setValue(100) except Exception as e: logging.exception("印花检测失败") QMessageBox.critical(mainWindow, "检测错误", f"检测过程中发生错误: {str(e)}", QMessageBox.Ok) finally: progress.close() def update_diff_display(diff_ratio, is_qualified): mainWindow.lblCurrentDiff.setText(f"当前差异度: {diff_ratio*100:.2f}%") if is_qualified: mainWindow.lblDiffStatus.setText("状态: 合格") mainWindow.lblDiffStatus.setStyleSheet("color: green; font-size: 12px;") else: mainWindow.lblDiffStatus.setText("状态: 不合格") mainWindow.lblDiffStatus.setStyleSheet("color: red; font-size: 12px;") def update_diff_threshold(value): mainWindow.lblDiffValue.setText(f"{value}%") def save_sample_image(): global isGrabbing, obj_cam_operation, current_sample_path if not isGrabbing: QMessageBox.warning(mainWindow, "错误", "请先开始取流并捕获图像!", QMessageBox.Ok) return # 检查是否有可用帧 if not obj_cam_operation.is_frame_available(): QMessageBox.warning(mainWindow, "无有效图像", "未捕获到有效图像,请检查相机状态!", QMessageBox.Ok) return settings = QSettings("ClothInspection", "CameraApp") last_dir = settings.value("last_save_dir", os.path.join(os.getcwd(), "captures")) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") default_filename = f"sample_{timestamp}" file_path, selected_filter = QFileDialog.getSaveFileName( mainWindow, "保存标准样本图像", os.path.join(last_dir, default_filename), "BMP Files (*.bmp);;PNG Files (*.png);;JPEG Files (*.jpg);;所有文件 (*)", options=QFileDialog.DontUseNativeDialog ) if not file_path: return file_extension = os.path.splitext(file_path)[1].lower() if not file_extension: if "BMP" in selected_filter: file_path += ".bmp" elif "PNG" in selected_filter: file_path += ".png" elif "JPEG" in selected_filter or "JPG" in selected_filter: file_path += ".jpg" else: file_path += ".bmp" file_extension = os.path.splitext(file_path)[1].lower() format_mapping = {".bmp": "bmp", ".png": "png", ".jpg": "jpg", ".jpeg": "jpg"} save_format = format_mapping.get(file_extension) if not save_format: QMessageBox.warning(mainWindow, "错误", "不支持的文件格式!", QMessageBox.Ok) return directory = os.path.dirname(file_path) if directory and not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as e: QMessageBox.critical(mainWindow, "目录创建错误", f"无法创建目录 {directory}: {str(e)}", QMessageBox.Ok) return try: ret = obj_cam_operation.save_image(file_path, save_format) if ret != MV_OK: strError = f"保存样本图像失败: {hex(ret)}" QMessageBox.warning(mainWindow, "错误", strError, QMessageBox.Ok) else: QMessageBox.information(mainWindow, "成功", f"标准样本已保存至:\n{file_path}", QMessageBox.Ok) current_sample_path = file_path update_sample_display() settings.setValue("last_save_dir", os.path.dirname(file_path)) except Exception as e: QMessageBox.critical(mainWindow, "异常错误", f"保存图像时发生错误: {str(e)}", QMessageBox.Ok) def preview_sample(): global current_sample_path if not current_sample_path or not os.path.exists(current_sample_path): QMessageBox.warning(mainWindow, "错误", "请先设置有效的标准样本图像!", QMessageBox.Ok) return try: img_data = np.fromfile(current_sample_path, dtype=np.uint8) sample_img = cv2.imdecode(img_data, cv2.IMREAD_COLOR) if sample_img is None: raise Exception("无法加载图像") cv2.imshow("标准样本预览", sample_img) cv2.waitKey(0) cv2.destroyAllWindows() except Exception as e: QMessageBox.warning(mainWindow, "错误", f"预览样本失败: {str(e)}", QMessageBox.Ok) def update_sample_display(): global current_sample_path if current_sample_path: mainWindow.lblSamplePath.setText(f"当前样本: {os.path.basename(current_sample_path)}") mainWindow.lblSamplePath.setToolTip(current_sample_path) mainWindow.bnPreviewSample.setEnabled(True) else: mainWindow.lblSamplePath.setText("当前样本: 未设置样本") mainWindow.bnPreviewSample.setEnabled(False) def update_history_display(): global detection_history mainWindow.cbHistory.clear() for i, result in enumerate(detection_history[-10:]): timestamp = result['timestamp'].strftime("%H:%M:%S") status = "合格" if result['qualified'] else "不合格" ratio = f"{result['diff_ratio']*100:.2f}%" mainWindow.cbHistory.addItem(f"[极客{timestamp}] {status} - 差异: {ratio}") def TxtWrapBy(start_str, end, all): start = all.find(start_str) if start >= 0: start += len(start_str) end = all.find(end, start) if end >= 0: return all[start:end].strip() def ToHexStr(num): if not isinstance(num, int): try: num = int(num) except: return f"<非整数:{type(num)}>" chaDic = {10: 'a', 11: 'b', 12: 'c', 13: 'd', 14: 'e', 15: 'f'} hexStr = "" if num < 0: num = num + 2 ** 32 while num >= 16: digit = num % 16 hexStr = chaDic.get(digit, str(digit)) + hexStr num //= 16 hexStr = chaDic.get(num, str(num)) + hexStr return "0x" + hexStr def decoding_char(c_ubyte_value): c_char_p_value = ctypes.cast(c_ubyte_value, ctypes.c_char_p) try: decode_str = c_char_p_value.value.decode('gbk') except UnicodeDecodeError: decode_str = str(c_char_p_value.value) return decode_str def enum_devices(): global deviceList, obj_cam_operation # 使用正确的常量方式 n_layer_type = ( MV_GIGE_DEVICE | MV_USB_DEVICE | MV_GENTL_CAMERALINK_DEVICE | MV_GENTL_CXP_DEVICE | MV_GENTL_XOF_DEVICE ) # 正确创建设备列表 deviceList = MV_CC_DEVICE_INFO_LIST() # 调用枚举函数 ret = MvCamera.MV_CC_EnumDevices(n_layer_type, deviceList) if ret != 0: strError = "Enum devices fail! ret = :" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) return ret if deviceList.nDeviceNum == 0: QMessageBox.warning(mainWindow, "Info", "Find no device", QMessageBox.Ok) return ret print(f"Find {deviceList.nDeviceNum} devices!") # 处理设备信息 devList = [] for i in range(0, deviceList.nDeviceNum): # 获取设备信息指针 device_info = deviceList.pDeviceInfo[i] # 转换为正确的结构体类型 mvcc_dev_info = cast(device_info, POINTER(MV_CC_DEVICE_INFO)).contents # 根据设备类型提取信息 - 关键修复:使用正确的结构体名称 if mvcc_dev_info.nTLayerType == MV_GIGE_DEVICE: # 处理GigE设备信息 - 使用正确的stGigEInfo try: # 尝试访问新版SDK的结构体 st_gige_info = mvcc_dev_info.SpecialInfo.stGigEInfo except AttributeError: try: # 尝试访问旧版SDK的结构体 st_gige_info = mvcc_dev_info.SpecialInfo.stGEInfo except AttributeError: # 如果两种结构体都不存在,使用默认值 devList.append(f"[{i}]GigE: Unknown Device") continue user_defined_name = decoding_char(st_gige_info.chUserDefinedName) model_name = decoding_char(st_gige_info.chModelName) nip1 = ((st_gige_info.nCurrentIp & 0xff000000) >> 24) nip2 = ((st_gige_info.nCurrentIp & 0x00ff0000) >> 16) nip3 = ((st_gige_info.nCurrentIp & 0x0000ff00) >> 8) nip4 = (st_gige_info.nCurrentIp & 0x000000ff) devList.append(f"[{i}]GigE: {user_defined_name} {model_name}({nip1}.{nip2}.{nip3}.{nip4})") elif mvcc_dev_info.nTLayerType == MV_USB_DEVICE: # 处理USB设备信息 try: st_usb_info = mvcc_dev_info.SpecialInfo.stUsb3VInfo except AttributeError: try: st_usb_info = mvcc_dev_info.SpecialInfo.stUsbInfo except AttributeError: devList.append(f"[{i}]USB: Unknown Device") continue user_defined_name = decoding_char(st_usb_info.chUserDefinedName) model_name = decoding_char(st_usb_info.chModelName) strSerialNumber = "" for per in st_usb_info.chSerialNumber: if per == 0: break strSerialNumber = strSerialNumber + chr(per) devList.append(f"[{i}]USB: {user_defined_name} {model_name}({strSerialNumber})") else: # 处理其他类型设备 devList.append(f"[{i}]Unknown Device Type: {mvcc_dev_info.nTLayerType}") # 更新UI mainWindow.ComboDevices.clear() mainWindow.ComboDevices.addItems(devList) mainWindow.ComboDevices.setCurrentIndex(0) # 更新状态栏 mainWindow.statusBar().showMessage(f"找到 {deviceList.nDeviceNum} 个设备", 3000) return MV_OK # ===== 关键改进:相机操作函数 ===== def open_device(): global deviceList, nSelCamIndex, obj_cam_operation, isOpen, frame_monitor_thread, mainWindow if isOpen: QMessageBox.warning(mainWindow, "Error", '相机已打开!', QMessageBox.Ok) return MV_E_CALLORDER nSelCamIndex = mainWindow.ComboDevices.currentIndex() if nSelCamIndex < 0: QMessageBox.warning(mainWindow, "Error", '请选择相机!', QMessageBox.Ok) return MV_E_CALLORDER # 创建相机控制对象 cam = MvCamera() # 初始化相机操作对象 - 确保传入有效的相机对象 obj_cam_operation = CameraOperation(cam, deviceList, nSelCamIndex) ret = obj_cam_operation.open_device() if 0 != ret: strError = "打开设备失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) isOpen = False else: set_continue_mode() get_param() isOpen = True enable_controls() # 创建并启动帧监控线程 frame_monitor_thread = FrameMonitorThread(obj_cam_operation) frame_monitor_thread.frame_status.connect(mainWindow.statusBar().showMessage) frame_monitor_thread.start() def start_grabbing(): global obj_cam_operation, isGrabbing # 关键改进:添加相机状态检查 if not obj_cam_operation or not hasattr(obj_cam_operation, 'cam') or not obj_cam_operation.cam: QMessageBox.warning(mainWindow, "Error", "相机对象未正确初始化", QMessageBox.Ok) return ret = obj_cam_operation.start_grabbing(mainWindow.widgetDisplay.winId()) if ret != 0: strError = "开始取流失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) else: isGrabbing = True enable_controls() # 等待第一帧到达 QThread.msleep(500) if not obj_cam_operation.is_frame_available(): QMessageBox.warning(mainWindow, "警告", "开始取流后未接收到帧,请检查相机连接!", QMessageBox.Ok) def stop_grabbing(): global obj_cam_operation, isGrabbing # 关键改进:添加相机状态检查 if not obj_cam_operation or not hasattr(obj_cam_operation, 'cam') or not obj_cam_operation.cam: QMessageBox.warning(mainWindow, "Error", "相机对象未正确初始化", QMessageBox.Ok) return # 关键改进:添加连接状态检查 if not hasattr(obj_cam_operation, 'connected') or not obj_cam_operation.connected: QMessageBox.warning(mainWindow, "Error", "相机未连接", QMessageBox.Ok) return ret = obj_cam_operation.Stop_grabbing() if ret != 0: strError = "停止取流失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) else: isGrabbing = False enable_controls() def close_device(): global isOpen, isGrabbing, obj_cam_operation, frame_monitor_thread if frame_monitor_thread and frame_monitor_thread.isRunning(): frame_monitor_thread.stop() frame_monitor_thread.wait(2000) if isOpen and obj_cam_operation: # 关键改进:确保相机对象存在 if hasattr(obj_cam_operation, 'cam') and obj_cam_operation.cam: obj_cam_operation.close_device() isOpen = False isGrabbing = False enable_controls() def set_continue_mode(): # 关键改进:添加相机状态检查 if not obj_cam_operation or not hasattr(obj_cam_operation, 'cam') or not obj_cam_operation.cam: return ret = obj_cam_operation.set_trigger_mode(False) if ret != 0: strError = "设置连续模式失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) else: mainWindow.radioContinueMode.setChecked(True) mainWindow.radioTriggerMode.setChecked(False) mainWindow.bnSoftwareTrigger.setEnabled(False) def set_software_trigger_mode(): # 关键改进:添加相机状态检查 if not obj_cam_operation or not hasattr(obj_cam_operation, 'cam') or not obj_cam_operation.cam: return ret = obj_cam_operation.set_trigger_mode(True) if ret != 0: strError = "设置触发模式失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) else: mainWindow.radioContinueMode.setChecked(False) mainWindow.radioTriggerMode.setChecked(True) mainWindow.bnSoftwareTrigger.setEnabled(isGrabbing) def trigger_once(): # 关键改进:添加相机状态检查 if not obj_cam_operation or not hasattr(obj_cam_operation, 'cam') or not obj_cam_operation.cam: return ret = obj_cam_operation.trigger_once() if ret != 0: strError = "软触发失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) def save_sample_image(): global isGrabbing, obj_cam_operation, current_sample_path if not isGrabbing: QMessageBox.warning(mainWindow, "错误", "请先开始取流并捕获图像!", QMessageBox.Ok) return # 尝试捕获当前帧 frame = obj_cam_operation.capture_frame() if frame is None: QMessageBox.warning(mainWindow, "无有效图像", "未捕获到有效图像,请检查相机状态!", QMessageBox.Ok) return # 确保图像有效 if frame.size == 0 or frame.shape[0] == 0 or frame.shape[1] == 0: QMessageBox.warning(mainWindow, "无效图像", "捕获的图像无效,请检查相机设置!", QMessageBox.Ok) return settings = QSettings("ClothInspection", "CameraApp") last_dir = settings.value("last_save_dir", os.path.join(os.getcwd(), "captures")) timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") default_filename = f"sample_{timestamp}" file_path, selected_filter = QFileDialog.getSaveFileName( mainWindow, "保存标准样本图像", os.path.join(last_dir, default_filename), "BMP Files (*.bmp);;PNG Files (*.png);;JPEG Files (*.jpg);;所有文件 (*)", options=QFileDialog.DontUseNativeDialog ) if not file_path: return # 确保文件扩展名正确 file_extension = os.path.splitext(file_path)[1].lower() if not file_extension: if "BMP" in selected_filter: file_path += ".bmp" elif "PNG" in selected_filter: file_path += ".png" elif "JPEG" in selected_filter or "JPG" in selected_filter: file_path += ".jpg" else: file_path += ".bmp" file_extension = os.path.splitext(file_path)[1].lower() # 创建目录(如果不存在) directory = os.path.dirname(file_path) if directory and not os.path.exists(directory): try: os.makedirs(directory, exist_ok=True) except OSError as e: QMessageBox.critical(mainWindow, "目录创建错误", f"无法创建目录 {directory}: {str(e)}", QMessageBox.Ok) return # 保存图像 try: # 使用OpenCV保存图像 if not cv2.imwrite(file_path, frame): raise Exception("OpenCV保存失败") # 更新状态 current_sample_path = file_path update_sample_display() settings.setValue("last_save_dir", os.path.dirname(file_path)) # 显示成功消息 QMessageBox.information(mainWindow, "成功", f"标准样本已保存至:\n{file_path}", QMessageBox.Ok) # 可选:自动预览样本 preview_sample() except Exception as e: logging.error(f"保存图像失败: {str(e)}") QMessageBox.critical(mainWindow, "保存错误", f"保存图像时发生错误:\n{str(e)}", QMessageBox.Ok) def preview_sample(): global current_sample_path if not current_sample_path or not os.path.exists(current_sample_path): QMessageBox.warning(mainWindow, "错误", "请先设置有效的标准样本图像!", QMessageBox.Ok) return try: # 直接使用OpenCV加载图像 sample_img = cv2.imread(current_sample_path) if sample_img is None: raise Exception("无法加载图像") # 显示图像 cv2.imshow("标准样本预览", sample_img) cv2.waitKey(0) cv2.destroyAllWindows() except Exception as e: QMessageBox.warning(mainWindow, "错误", f"预览样本失败: {str(e)}", QMessageBox.Ok) def start_grabbing(): global obj_cam_operation, isGrabbing ret = obj_cam_operation.start_grabbing(mainWindow.widgetDisplay.winId()) if ret != 0: strError = "开始取流失败 ret:" + ToHexStr(ret) QMessageBox.warning(mainWindow, "Error", strError, QMessageBox.Ok) else: isGrabbing = True enable_controls() # 等待第一帧到达 QThread.msleep(500) if not obj_cam_operation.is_frame_available(): QMessageBox.warning(mainWindow, "警告", "开始取流后未接收到帧,请检查相机连接!", QMessageBox.Ok) def is_float(str): try: float(str) return True except ValueError: return False def get_param(): try: ret = obj_cam_operation.get_parameters() if ret != MV_OK: strError = "获取参数失败,错误码: " + ToHexStr(ret) QMessageBox.warning(mainWindow, "错误", strError, QMessageBox.Ok) else: mainWindow.edtExposureTime.setText("{0:.2f}".format(obj_cam_operation.exposure_time)) mainWindow.edtGain.setText("{0:.2f}".format(obj_cam_operation.gain)) mainWindow.edtFrameRate.setText("{0:.2f}".format(obj_cam_operation.frame_rate)) except Exception as e: error_msg = f"获取参数时发生错误: {str(e)}" QMessageBox.critical(mainWindow, "严重错误", error_msg, QMessageBox.Ok) def set_param(): frame_rate = mainWindow.edtFrameRate.text() exposure = mainWindow.edtExposureTime.text() gain = mainWindow.edtGain.text() if not (is_float(frame_rate) and is_float(exposure) and is_float(gain)): strError = "设置参数失败: 参数必须是有效的浮点数" QMessageBox.warning(mainWindow, "错误", strError, QMessageBox.Ok) return MV_E_PARAMETER try: ret = obj_cam_operation.set_param( frame_rate=float(frame_rate), exposure_time=float(exposure), gain=float(gain) ) if ret != MV_OK: strError = "设置参数失败,错误码: " + ToHexStr(ret) QMessageBox.warning(mainWindow, "错误", strError, QMessageBox.Ok) except Exception as e: error_msg = f"设置参数时发生错误: {str(e)}" QMessageBox.critical(mainWindow, "严重错误", error_msg, QMessageBox.Ok) def enable_controls(): global isGrabbing, isOpen mainWindow.groupGrab.setEnabled(isOpen) mainWindow.paramgroup.setEnabled(isOpen) mainWindow.bnOpen.setEnabled(not isOpen) mainWindow.bnClose.setEnabled(isOpen) mainWindow.bnStart.setEnabled(isOpen and (not isGrabbing)) mainWindow.bnStop.setEnabled(isOpen and isGrabbing) mainWindow.bnSoftwareTrigger.setEnabled(isGrabbing and mainWindow.radioTriggerMode.isChecked()) mainWindow.bnSaveImage.setEnabled(isOpen and isGrabbing) mainWindow.bnCheckPrint.setEnabled(isOpen and isGrabbing) mainWindow.bnSaveSample.setEnabled(isOpen and isGrabbing) mainWindow.bnPreviewSample.setEnabled(bool(current_sample_path)) def update_sensor_display(data): if not data: return text = (f"张力: {data['tension']:.2f}N | " f"速度: {data['speed']:.2f}m/s | " f"温度: {data['temperature']:.1f}°C | " f"湿度: {data['humidity']:.1f}%") mainWindow.lblSensorData.setText(text) def connect_sensor(): global sensor_monitor_thread, sensor_controller sensor_type = mainWindow.cbSensorType.currentText() if sensor_controller is None: sensor_controller = SensorController() if sensor_type == "串口": config = { 'type': 'serial', 'port': mainWindow.cbComPort.currentText(), 'baudrate': int(mainWindow.cbBaudrate.currentText()), 'timeout': 1.0 } else: config = { 'type': 'ethernet', 'ip': mainWindow.edtIP.text(), 'port': int(mainWindow.edtPort.text()), 'timeout': 1.0 } if sensor_controller.connect(config): mainWindow.bnConnectSensor.setEnabled(False) mainWindow.bnDisconnectSensor.setEnabled(True) sensor_monitor_thread = SensorMonitorThread(sensor_controller) sensor_monitor_thread.data_updated.connect(update_sensor_display) sensor_monitor_thread.start() def disconnect_sensor(): global sensor_monitor_thread if sensor_controller: sensor_controller.disconnect() mainWindow.bnConnectSensor.setEnabled(True) mainWindow.bnDisconnectSensor.setEnabled(False) if sensor_monitor_thread and sensor_monitor_thread.isRunning(): sensor_monitor_thread.stop() sensor_monitor_thread.wait(2000) sensor_monitor_thread = None mainWindow.lblSensorData.setText("传感器数据: 未连接") def update_sensor_ui(index): mainWindow.serialGroup.setVisible(index == 0) mainWindow.ethernetGroup.setVisible(index == 1) class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("布料印花检测系统") self.resize(1200, 800) central_widget = QWidget() self.setCentralWidget(central_widget) main_layout = QVBoxLayout(central_widget) # 设备枚举区域 device_layout = QHBoxLayout() self.ComboDevices = QComboBox() self.bnEnum = QPushButton("枚举设备") self.bnOpen = QPushButton("打开设备") self.bnClose = QPushButton("关闭设备") device_layout.addWidget(self.ComboDevices) device_layout.addWidget(self.bnEnum) device_layout.addWidget(self.bnOpen) device_layout.addWidget(self.bnClose) main_layout.addLayout(device_layout) # 取流控制组 self.groupGrab = QGroupBox("取流控制") grab_layout = QHBoxLayout(self.groupGrab) self.bnStart = QPushButton("开始取流") self.bnStop = QPushButton("停止取流") self.radioContinueMode = QRadioButton("连续模式") self.radioTriggerMode = QRadioButton("触发模式") self.bnSoftwareTrigger = QPushButton("软触发") grab_layout.addWidget(self.bnStart) grab_layout.addWidget(self.bnStop) grab_layout.addWidget(self.radioContinueMode) grab_layout.addWidget(self.radioTriggerMode) grab_layout.addWidget(self.bnSoftwareTrigger) main_layout.addWidget(self.groupGrab) # 参数设置组 self.paramgroup = QGroupBox("相机参数") param_layout = QGridLayout(self.paramgroup) self.edtExposureTime = QLineEdit() self.edtGain = QLineEdit() self.edtFrameRate = QLineEdit() self.bnGetParam = QPushButton("获取参数") self.bnSetParam = QPushButton("设置参数") self.bnSaveImage = QPushButton("保存图像") param_layout.addWidget(QLabel("曝光时间:"), 0, 0) param_layout.addWidget(self.edtExposureTime, 0, 1) param_layout.addWidget(self.bnGetParam, 0, 2) param_layout.addWidget(QLabel("增益:"), 1, 0) param_layout.addWidget(self.edtGain, 1, 1) param_layout.addWidget(self.bnSetParam, 1, 2) param_layout.addWidget(QLabel("帧率:"), 2, 0) param_layout.addWidget(self.edtFrameRate, 2, 1) param_layout.addWidget(self.bnSaveImage, 2, 2) main_layout.addWidget(self.paramgroup) # 图像显示区域 self.widgetDisplay = QLabel() self.widgetDisplay.setMinimumSize(640, 480) self.widgetDisplay.setStyleSheet("background-color: black;") self.widgetDisplay.setAlignment(Qt.AlignCenter) self.widgetDisplay.setText("相机预览区域") main_layout.addWidget(self.widgetDisplay, 1) # 状态栏 #self.statusBar = QStatusBar() #self.setStatusBar(self.statusBar) # 创建自定义UI组件 self.setup_custom_ui() def setup_custom_ui(self): # 工具栏 toolbar = self.addToolBar("检测工具") self.bnCheckPrint = QPushButton("检测印花质量") self.bnSaveSample = QPushButton("保存标准样本") self.bnPreviewSample = QPushButton("预览样本") self.cbHistory = QComboBox() self.cbHistory.setMinimumWidth(300) toolbar.addWidget(self.bnCheckPrint) toolbar.addWidget(self.bnSaveSample) toolbar.addWidget(self.bnPreviewSample) toolbar.addWidget(QLabel("历史记录:")) toolbar.addWidget(self.cbHistory) # 状态栏样本路径 self.lblSamplePath = QLabel("当前样本: 未设置样本") self.statusBar().addPermanentWidget(self.lblSamplePath) # 右侧面板 right_panel = QWidget() right_layout = QVBoxLayout(right_panel) right_layout.setContentsMargins(10, 10, 10, 10) # 差异度调整组 diff_group = QGroupBox("差异度调整") diff_layout = QVBoxLayout(diff_group) self.lblDiffThreshold = QLabel("差异度阈值 (0-100%):") self.sliderDiffThreshold = QSlider(Qt.Horizontal) self.sliderDiffThreshold.setRange(0, 100) self.sliderDiffThreshold.setValue(5) self.lblDiffValue = QLabel("5%") self.lblCurrentDiff = QLabel("当前差异度: -") self.lblCurrentDiff.setStyleSheet("font-size: 14px; font-weight: bold;") self.lblDiffStatus = QLabel("状态: 未检测") self.lblDiffStatus.setStyleSheet("font-size: 12px;") diff_layout.addWidget(self.lblDiffThreshold) diff_layout.addWidget(self.sliderDiffThreshold) diff_layout.addWidget(self.lblDiffValue) diff_layout.addWidget(self.lblCurrentDiff) diff_layout.addWidget(self.lblDiffStatus) right_layout.addWidget(diff_group) # 传感器控制面板 sensor_panel = QGroupBox("传感器控制") sensor_layout = QVBoxLayout(sensor_panel) sensor_type_layout = QHBoxLayout() self.lblSensorType = QLabel("传感器类型:") self.cbSensorType = QComboBox() self.cbSensorType.addItems(["串口", "以太网"]) sensor_type_layout.addWidget(self.lblSensorType) sensor_type_layout.addWidget(self.cbSensorType) sensor_layout.addLayout(sensor_type_layout) # 串口参数 self.serialGroup = QGroupBox("串口参数") serial_layout = QVBoxLayout(self.serialGroup) self.lblComPort = QLabel("端口:") self.cbComPort = QComboBox() if platform.system() == 'Windows': ports = [f"COM{i}" for i in range(1, 21)] else: ports = [f"/dev/ttyS{i}" for i in range(0, 4)] + [f"/dev/ttyUSB{i}" for i in range(0, 4)] self.cbComPort.addItems(ports) self.lblBaudrate = QLabel("波特率:") self.cbBaudrate = QComboBox() self.cbBaudrate.addItems(["96000", "19200", "38400", "57600", "115200"]) self.cbBaudrate.setCurrentText("115200") serial_layout.addWidget(self.lblComPort) serial_layout.addWidget(self.cbComPort) serial_layout.addWidget(self.lblBaudrate) serial_layout.addWidget(self.cbBaudrate) sensor_layout.addWidget(self.serialGroup) # 以太网参数 self.ethernetGroup = QGroupBox("以太网参数") ethernet_layout = QVBoxLayout(self.ethernetGroup) self.lblIP = QLabel("IP地址:") self.edtIP = QLineEdit("192.168.1.100") self.lblPort = QLabel("端口:") self.edtPort = QLineEdit("502") ethernet_layout.addWidget(self.lblIP) ethernet_layout.addWidget(self.edtIP) ethernet_layout.addWidget(self.lblPort) ethernet_layout.addWidget(self.edtPort) sensor_layout.addWidget(self.ethernetGroup) # 连接按钮 self.bnConnectSensor = QPushButton("连接传感器") self.bnDisconnectSensor = QPushButton("断开传感器") self.bnDisconnectSensor.setEnabled(False) sensor_layout.addWidget(self.bnConnectSensor) sensor_layout.addWidget(self.bnDisconnectSensor) # 延迟设置 delay_layout = QHBoxLayout() self.lblDelay = QLabel("触发延迟(秒):") self.spinDelay = QSpinBox() self.spinDelay.setRange(0, 60) self.spinDelay.setValue(0) self.spinDelay.setToolTip("传感器检测到布料后延迟拍摄的时间") delay_layout.addWidget(self.lblDelay) delay_layout.addWidget(self.spinDelay) sensor_layout.addLayout(delay_layout) # 传感器数据 self.lblSensorData = QLabel("传感器数据: 未连接") self.lblSensorData.setStyleSheet("font-size: 10pt;") sensor_layout.addWidget(self.lblSensorData) right_layout.addWidget(sensor_panel) right_layout.addStretch(1) # 停靠窗口 dock = QDockWidget("检测控制面板", self) dock.setWidget(right_panel) dock.setFeatures(QDockWidget.DockWidgetMovable | QDockWidget.DockWidgetFloatable) self.addDockWidget(Qt.RightDockWidgetArea, dock) def closeEvent(self, event): logging.info("主窗口关闭,执行清理...") close_device() disconnect_sensor() event.accept() if __name__ == "__main__": app = QApplication(sys.argv) mainWindow = MainWindow() # 信号连接 mainWindow.cbSensorType.currentIndexChanged.connect(update_sensor_ui) update_sensor_ui(0) mainWindow.bnConnectSensor.clicked.connect(connect_sensor) mainWindow.bnDisconnectSensor.clicked.connect(disconnect_sensor) mainWindow.sliderDiffThreshold.valueChanged.connect(update_diff_threshold) mainWindow.bnCheckPrint.clicked.connect(sensor_controlled_check) mainWindow.bnSaveSample.clicked.connect(save_sample_image) mainWindow.bnPreviewSample.clicked.connect(preview_sample) mainWindow.bnEnum.clicked.connect(enum_devices) mainWindow.bnOpen.clicked.connect(open_device) mainWindow.bnClose.clicked.connect(close_device) mainWindow.bnStart.clicked.connect(start_grabbing) mainWindow.bnStop.clicked.connect(stop_grabbing) mainWindow.bnSoftwareTrigger.clicked.connect(trigger_once) mainWindow.radioTriggerMode.clicked.connect(set_software_trigger_mode) mainWindow.radioContinueMode.clicked.connect(set_continue_mode) mainWindow.bnGetParam.clicked.connect(get_param) mainWindow.bnSetParam.clicked.connect(set_param) mainWindow.bnSaveImage.clicked.connect(save_sample_image) main() mainWindow.show() app.exec_() close_device() disconnect_sensor() sys.exit() 我想把这个程序打包成exe文件我该怎么做
最新发布
07-12
<think>为了将Python程序打包成可执行的EXE文件,我们通常使用PyInstaller工具。以下是详细的步骤和注意事项,特别是针对这个布料印花检测系统(包含海康威视相机SDK、OpenCV、PyQt5等复杂依赖)的打包过程。 ### 步骤概述: 1. **安装PyInstaller**:使用pip安装PyInstaller。 2. **准备程序入口**:确保程序有一个明确的入口脚本(如`main.py`)。 3. **处理路径问题**:在代码中处理资源路径和动态链接库路径,特别是对于海康SDK的DLL。 4. **创建spec文件**(可选):对于复杂项目,可能需要创建一个spec文件来配置打包选项。 5. **运行PyInstaller**:执行打包命令。 6. **测试EXE文件**:在目标机器上测试运行。 ### 详细步骤: #### 1. 安装PyInstaller ```bash pip install pyinstaller ``` #### 2. 确保程序入口 假设你的主程序文件名为`cloth_inspection.py`,并且程序启动是通过执行这个文件。 #### 3. 代码调整 在打包前,需要调整代码中的路径问题,特别是对于海康SDK的DLL加载。在代码中已经有一个`fix_sdk_path()`函数,它在打包模式下会调整路径。但是,在打包时需要确保DLL文件被正确包含。 #### 4. 创建spec文件(可选) 由于项目复杂,建议创建一个spec文件来配置打包。下面是一个示例spec文件(`cloth_inspection.spec`)的内容: ```python # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['cloth_inspection.py'], pathex=[], binaries=[], datas=[ # 包含海康SDK的DLL文件(根据你的实际路径调整) ('D:\\海康\\MVS\\Runtime\\Win64\\MvCamCtrldll.dll', '.'), # 包含其他必要的文件,比如标准样本图像(可选) # ('samples/*.bmp', 'samples'), ], hiddenimports=[], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='cloth_inspection', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=False, # 如果不需要控制台窗口,设置为False icon='app_icon.ico', # 可选,设置图标 ) ``` **注意**: - 你需要将海康SDK的DLL文件(`MvCamCtrldll.dll`)包含进来。根据你的SDK安装位置,找到这个DLL文件(注意32位和64位,这里假设是64位系统,路径为`D:\海康\MVS\Runtime\Win64\MvCamCtrldll.dll`)。 - 如果程序使用了其他资源文件(如图像、配置文件),也要在`datas`中指定。 - 如果程序有图标,可以设置`icon`参数。 #### 5. 运行PyInstaller 使用以下命令运行PyInstaller(使用spec文件): ```bash pyinstaller cloth_inspection.spec ``` 或者,如果不使用spec文件,可以使用命令行参数: ```bash pyinstaller --onefile --windowed --add-binary "D:\海康\MVS\Runtime\Win64\MvCamCtrldll.dll;." --add-data "samples;." --icon app_icon.ico cloth_inspection.py ``` 解释: - `--onefile`:打包成单个EXE文件。 - `--windowed`:不显示控制台窗口(适用于GUI程序)。 - `--add-binary`:添加二进制文件(DLL),格式为`源路径;目标路径`(目标路径为打包后的根目录,用`.`表示)。 - `--add-data`:添加数据文件(如图片、配置文件),格式同上。 - `--icon`:设置EXE的图标。 #### 6. 测试EXE文件 打包完成后,EXE文件位于`dist`目录下。在运行之前,确保目标机器满足以下条件: - 安装海康相机驱动(如果使用海康相机)。 - 安装必要的VC++运行库(通常需要安装Visual C++ Redistributable for Visual Studio 2015-2019)。 然后,运行EXE文件进行测试。 ### 常见问题及解决方案: 1. **DLL加载失败**: - 确保DLL被正确包含在打包文件中(使用`--add-binary`或在spec文件中指定)。 - 在代码中,使用`sys._MEIPASS`来定位打包后的资源路径(在`fix_sdk_path()`函数中已经处理了)。 2. **OpenCV相关错误**: - 确保打包时包含了OpenCV所需的额外文件(如`.npy`文件)。PyInstaller通常能自动处理OpenCV,但有时需要手动添加。可以尝试添加: ```bash --add-data "C:\Python\Lib\site-packages\cv2;cv2" ``` 3. **PyQt5相关错误**: - PyInstaller通常能正确处理PyQt5。如果遇到样式问题,可能需要添加Qt插件。例如: ```python # 在代码中添加 import os os.environ["QT_PLUGIN_PATH"] = os.path.join(sys._MEIPASS, "PyQt5", "Qt", "plugins") ``` 4. **路径问题**: - 在代码中,所有文件路径都应该使用`os.path.join`,并且使用`sys._MEIPASS`来获取打包后的资源路径。 ### 打包后的文件结构: 在`dist`目录下,你会有一个`cloth_inspection`文件夹(或单个EXE文件),里面包含: - `cloth_inspection.exe`:主程序。 - `MvCamCtrldll.dll`:海康SDK的DLL。 - 其他依赖的DLL和资源文件。 ### 注意事项: - 由于海康SDK是硬件相关的,打包后的程序在目标机器上需要安装相应的相机驱动。 - 如果使用`--onefile`打包,程序启动时会解压到临时目录,因此初始启动会稍慢。 - 对于复杂的项目,建议先使用`--onedir`(默认)打包成目录,测试无误后再尝试`--onefile`。 ### 示例代码调整(路径处理): 在`fix_sdk_path()`函数中,我们已经考虑了打包模式(`sys.frozen`)的情况。确保在打包后,DLL能被正确加载。 ### 最后,提供一个简单的打包脚本(`build_exe.py`): ```python import os import sys import subprocess # 打包命令 cmd = [ 'pyinstaller', '--onefile', '--windowed', '--add-binary', r'D:\海康\MVS\Runtime\Win64\MvCamCtrldll.dll;.', # 注意路径 '--icon', 'app_icon.ico', # 如果有图标 'cloth_inspection.py' ] subprocess.run(cmd, check=True) ``` 运行这个脚本即可打包。 ### 相关问题: §§相关问题§§: 1. 如何解决PyInstaller打包后程序启动时出现的“Failed to execute script”错误? 2. 打包时如何包含数据文件(如图片、配置文件)? 3. 如何为PyInstaller打包的EXE文件添加版本信息和图标? 4. 打包后如何减少EXE文件的体积?</think># 将Python程序打包成EXE文件 要将你的布料印花检测系统打包成独立的EXE文件,可以使用PyInstaller工具。以下是详细的步骤和解决方案: ## 打包步骤 ### 1. 安装PyInstaller ```bash pip install pyinstaller ``` ### 2. 创建打包配置文件 在你的项目目录中创建一个`build.spec`文件,内容如下: ```python # -*- mode: python ; coding: utf-8 -*- block_cipher = None a = Analysis( ['your_main_file.py'], # 替换为你的主Python文件名 pathex=[], binaries=[], datas=[ # 包含海康SDK的DLL文件 ('D:\\海康\\MVS\\Runtime\\Win64\\MvCamCtrldll.dll', '.'), # 包含其他必要的DLL文件 ('D:\\海康\\MVS\\Runtime\\Win64\\MvCameraControl.dll', '.'), ('D:\\海康\\MVS\\Runtime\\Win64\\MvGenTL.dll', '.'), # 包含OpenCV的DLL文件 ('C:\\Python\\Lib\\site-packages\\cv2\\*.dll', 'cv2'), # 包含PyQt5的插件 ('C:\\Python\\Lib\\site-packages\\PyQt5\\Qt5\\plugins\\*', 'PyQt5/Qt/plugins'), ], hiddenimports=[ 'PyQt5.QtCore', 'PyQt5.QtGui', 'PyQt5.QtWidgets', 'cv2', 'numpy', 'skimage', 'skimage.metrics', 'skimage.measure', 'serial', 'socket', 'logging', 'ctypes', 'ctypes.wintypes', ], hookspath=[], hooksconfig={}, runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False, ) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE( pyz, a.scripts, [], exclude_binaries=True, name='ClothInspectionSystem', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, console=False, # 设置为False以隐藏控制台窗口 icon='app_icon.ico', # 可选:添加应用图标 ) coll = COLLECT( exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='ClothInspectionSystem', ) ``` ### 3. 修改代码以适应打包环境 在你的主Python文件中添加以下路径处理代码: ```python # 在程序开头添加 import sys import os def resource_path(relative_path): """获取打包后资源的绝对路径""" try: # PyInstaller创建的临时文件夹路径 base_path = sys._MEIPASS except Exception: base_path = os.path.abspath(".") return os.path.join(base_path, relative_path) # 在SDK路径修复函数中使用 def fix_sdk_path(): """修复海康SDK的加载路径""" if getattr(sys, 'frozen', False): # 打包模式 base_path = sys._MEIPASS mvimport_path = os.path.join(base_path, "MvImport") if mvimport_path not in sys.path: sys.path.insert(0, mvimport_path) if sys.platform == 'win32': os.environ['PATH'] = base_path + os.pathsep + os.environ['PATH'] try: # 使用资源路径函数 dll_path = resource_path("MvCamCtrldll.dll") ctypes.WinDLL(dll_path) except OSError as e: print(f"核心DLL加载失败: {e}") sys.exit(1) else: # 开发模式 # 原有的开发模式路径处理... ``` ### 4. 创建打包脚本 创建一个`build.bat`文件来简化打包过程: ```batch @echo off setlocal rem 设置Python路径(根据你的实际安装路径) set PYTHON_PATH=C:\Python\Python39 rem 设置项目路径 set PROJECT_PATH=%~dp0 rem 设置海康SDK路径 set HK_SDK_PATH=D:\海康\MVS\Runtime\Win64 rem 创建临时目录 mkdir build_temp cd build_temp rem 复制必要的文件 copy %HK_SDK_PATH%\MvCamCtrldll.dll . copy %HK_SDK_PATH%\MvCameraControl.dll . copy %HK_SDK_PATH%\MvGenTL.dll . rem 复制OpenCV DLL copy %PYTHON_PATH%\Lib\site-packages\cv2\*.dll . rem 运行PyInstaller %PYTHON_PATH%\Scripts\pyinstaller.exe --onefile --windowed --add-data "MvCamCtrldll.dll;." --add-data "MvCameraControl.dll;." --add-data "MvGenTL.dll;." --add-data "*.dll;cv2" --icon %PROJECT_PATH%\app_icon.ico %PROJECT_PATH%\your_main_file.py rem 清理临时文件 cd .. rmdir /s /q build_temp echo 打包完成!输出文件在 dist 目录 endlocal ``` ### 5. 解决常见问题 #### 问题1:海康SDK加载失败 **解决方案**: 1. 确保所有必要的DLL文件(MvCamCtrldll.dll, MvCameraControl.dll, MvGenTL.dll)都包含在打包中 2. 在代码中使用`resource_path()`函数处理DLL路径 #### 问题2:OpenCV无法找到模块 **解决方案**: 1. 在spec文件中添加OpenCV的隐藏导入 2. 包含OpenCV的DLL文件 #### 问题3:PyQt5插件缺失 **解决方案**: 在spec文件中添加PyQt5插件路径: ```python datas=[ # ... ('C:\\Python\\Lib\\site-packages\\PyQt5\\Qt5\\plugins\\*', 'PyQt5/Qt/plugins'), ], ``` #### 问题4:打包后程序启动慢 **解决方案**: 1. 使用UPX压缩可执行文件 2. 在spec文件中设置`upx=True` 3. 下载UPX并放在PyInstaller目录下 ## 完整打包流程 1. 确保所有依赖已安装: ```bash pip install pyinstaller opencv-python numpy scikit-image pyserial pyqt5 ``` 2. 创建`app_icon.ico`文件(可选,用于应用图标) 3. 修改主Python文件中的路径处理代码(添加`resource_path()`函数) 4. 创建`build.spec`文件 5. 创建`build.bat`打包脚本 6. 运行打包脚本: ```batch build.bat ``` 7. 测试生成的EXE文件: - 在`dist`目录中找到`ClothInspectionSystem.exe` - 在目标机器上运行(无需安装Python环境) ## 注意事项 1. **海康SDK版本**:确保使用与开发环境相同的SDK版本 2. **目标系统**:打包环境与运行环境应一致(如都是64位Windows) 3. **依赖管理**:使用虚拟环境确保依赖版本一致 4. **文件路径**:所有文件路径使用`resource_path()`函数处理 5. **日志文件**:确保程序有写入日志文件的权限 ## 相关问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值