[Python] Matplotlib 與 cv2 的 QT 衝突
有時候編譯 opencv 程式會出現:
[Python] Matplotlib 與 cv2 的 QT 衝突
有時候編譯 opencv 程式會出現:
QObject::moveToThread: Current thread (0x5573ee556ad0) is not the object's thread (0x5573edbdad10).
Cannot move to target thread (0x5573ee556ad0)
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/uncle/.local/lib/python3.10/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
Available platform plugins are: xcb, eglfs, linuxfb, minimal, minimalegl, offscreen, vnc, wayland-egl, wayland, wayland-xcomposite-egl, wayland-xcomposite-glx.
Aborted (core dumped)
這個問題原因是混用了兩套 Qt。這支程式同時用到 Matplotlib(Qt5Agg) 與 OpenCV 自帶的 Qt plugin。兩邊 Qt/插件版本不同或載入順序錯誤 → “找得到 xcb 但載不進去”。
但偶爾其他程式同時 import matplotlib 和 cv2 執行起來都正常,有可能是因為也許只用 cv2.imshow()(沒 import matplotlib),所以只載一套 Qt → 不會衝突。
GUI 呼叫發生在非主執行緒 Log 裡的 QObject::moveToThread 就是在抱怨 Qt 物件被丟來丟去。
解決方法:(直接改用 TkAgg,有視窗但不碰 Qt,但前提是:要安裝 tk)
# 把可能干擾 Qt 的變數全部拔掉
import matplotlib.pyplot as plt
import os, matplotlib, sys
for v in ("QT_PLUGIN_PATH", "QT_QPA_PLATFORM_PLUGIN_PATH", "QT_QPA_PLATFORM"):
os.environ.pop(v, None)
os.environ["MPLBACKEND"] = "TkAgg" # 保險 메타데이터
- post_id
- a4450e86490c
- slug
- python-matplotlib-與-cv2-的-qt-衝突-a4450e86490c
- url
- https://medium.com/@aheadmb/python-matplotlib-%E8%88%87-cv2-%E7%9A%84-qt-%E8%A1%9D%E7%AA%81-a4450e86490c
- canonical_url
- https://medium.com/@aheadmb/python-matplotlib-%E8%88%87-cv2-%E7%9A%84-qt-%E8%A1%9D%E7%AA%81-a4450e86490c
- author_url
- https://medium.com/@aheadmb
- status
- ok
- fetched_at
- 2026-06-25 07:00:49