Python | OpenCV 圖片儲存與格式轉換
📚 前言
在上一篇 圖片讀取與顯示 中,我們學會了如何讀取與顯示圖片。
這一篇要進一步學習 圖片儲存與格式轉換,這是圖片處理的基本操作之一。
💾 儲存圖片
OpenCV 提供 cv2.imwrite() 來儲存圖片。官方文件
語法:
1
| cv2.imwrite(filename, img[, params])
|
- filename:檔案路徑與名稱(副檔名決定輸出格式)。
- img:要儲存的圖片(NumPy 陣列)。
- params:非必填,壓縮品質或其他設定。
🔄 格式轉換
只要改副檔名,就能轉換格式:
1 2 3 4 5 6 7 8 9
| import cv2
img = cv2.imread("assets/test.png")
cv2.imwrite("output/output.jpg", img) cv2.imwrite("output/output.png", img) cv2.imwrite("output/output.bmp", img)
|
常見格式:
- JPG:有壓縮,檔案小,但可能失真。
- PNG:無損壓縮,支援透明度。
- BMP:未壓縮,檔案大。

圖:將 PNG 轉換為 JPG、BMP 的效果
⚙️ 壓縮品質設定
不同格式支援不同的壓縮參數:
- JPG:可設定壓縮品質(0–100,數字越高品質越好,檔案越大)。
- PNG:可設定壓縮等級(0–9,數字越高壓縮率越高,速度越慢)。
範例:
1 2 3 4 5
| # 儲存高品質 JPG cv2.imwrite("high_quality.jpg", img, [cv2.IMWRITE_JPEG_QUALITY, 95])
# 儲存高壓縮 PNG cv2.imwrite("compressed.png", img, [cv2.IMWRITE_PNG_COMPRESSION, 9])
|
💻 範例程式:圖片儲存與格式轉換
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| import cv2 import os
img = cv2.imread("assets/test.png")
files = { "output/output.jpg": (img, []), "output/output.png": (img, []), "output/output.bmp": (img, []), "output/output_high.jpg": (img, [cv2.IMWRITE_JPEG_QUALITY, 95]), "output/output_compressed.png": (img, [cv2.IMWRITE_PNG_COMPRESSION, 9]), }
for path, (image, params) in files.items(): cv2.imwrite(path, image, params) if params else cv2.imwrite(path, image) size_kb = os.path.getsize(path) / 1024 print(f"{path:<35} {size_kb:>8.1f} KB")
|

圖:不同壓縮品質的 JPG 與 PNG 儲存結果
🖼️ 從 NumPy 陣列生成圖片
除了讀取現有圖片,也能直接用 NumPy 建立圖片矩陣,再用 imwrite() 儲存:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| import cv2 import numpy as np
img = np.zeros((500, 500, 3), dtype="uint8")
img[150:350, 150:350] = [0, 0, 255]
cv2.imwrite("output/red_square.jpg", img)
cv2.imshow('red_square', img) cv2.waitKey(0) cv2.destroyAllWindows()
|
👉 這樣就能快速生成一張 500×500 的黑底紅方塊圖片。

圖:使用 NumPy 建立黑底紅方塊並儲存
⚠️ 注意事項
- 副檔名決定格式:
imwrite() 會依檔名副檔名決定輸出格式。
- 顏色通道:OpenCV 使用 BGR,不是 RGB。
- 壓縮參數:不同格式支援的參數不同,詳細可查 ImwriteFlags。
🎯 結語
這一篇我們學會了如何使用 cv2.imwrite() 儲存圖片,並進行格式轉換與壓縮設定。
下一篇進入 影片讀取與播放,學習如何處理動態影像。
📖 如在學習過程中遇到疑問,或是想了解更多相關主題,建議回顧一下 Python | OpenCV 系列導讀,掌握完整的章節目錄,方便快速找到你需要的內容。
註:以上參考了
OpenCV Tutorials
OpenCV-Python Tutorials