/允安B
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.

      Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

      Explore these features while you wait
      Complete general settings
      Bookmark and like published notes
      Write a few more notes
      Complete general settings
      Write a few more notes
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note No publishing access yet

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.

    Your account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Your team account was recently created. Publishing will be available soon, allowing you to share notes on your public page and in search results.

    Explore these features while you wait
    Complete general settings
    Bookmark and like published notes
    Write a few more notes
    Complete general settings
    Write a few more notes
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # [ OpenCV ] 學習歷程筆記 使用程式語言:python 使⽤套件:cv2 作者:允安B --- 這份教學將帶您進入 OpenCV 的世界,特別針對圖像處理的入門內容。我們會從基本概念開始,逐步介紹如何使用 OpenCV 處理圖片,並提供實用的程式碼範例。無論您是初學者還是想快速複習,這個教學都會幫到您! ## 基本介紹 什麼是 OpenCV? OpenCV(Open Source Computer Vision Library)是一個功能強大的開源電腦視覺函式庫,專為圖像和影片處理設計。它就像一個工具箱,裡面裝滿了各種圖像處理的工具,從簡單的縮放、旋轉,到複雜的人臉辨識、物件追蹤,應有盡有。搭配 Python 的 NumPy 庫,OpenCV 能高效處理圖像數據,讓您用幾行程式碼實現專業效果。例如,您可以用它把彩色照片變成黑白素描,或從影片中提取重要畫面。 ## 安裝 OpenCV 在開始之前,您需要安裝 OpenCV。請確保您的電腦已有 Python(建議版本 3.7 或以上)和 pip。安裝步驟很簡單: 打開終端機(Windows 用 CMD 或 PowerShell,macOS/Linux 用 Terminal)。 輸入以下指令: `pip install opencv-python` 安裝完成後,檢查是否成功: `print(cv2.__version__)` 如果顯示版本號(例如 4.10.0),就表示成功了!若失敗,可嘗試更新 pip: `pip install --upgrade pip` 注意:若您的系統有多個 Python 版本,確保使用正確的 pip(例如 pip3)。Windows 用戶若遇到問題,可考慮用 Anaconda 建立虛擬環境。 ## 圖片檔案與路徑 在使用 OpenCV 讀取圖片時,檔案路徑非常重要。以下是基本原則: 建議也是最直覺的作法是將圖片(例如 image.jpg)放在與 Python 腳本同一資料夾。 ``` project_folder/ ├── script.py ├── image.jpg ``` 這樣只需用檔名即可讀取: `image = cv2.imread('image.jpg')` ### 相對路徑 如果圖片在子資料夾,例如 ``` project_folder/ ├── script.py ├── allimage/ image1.jpg ``` 則可寫:`image = cv2.imread('allimage/image1.png')` ### 絕對路徑 如果圖片在其他地方,你也可以直接寫完整路徑,例如: ``` Windows:C:/Users/YourName/project_folder/image.jpg macOS/Linux:/home/yourname/project_folder/image.jpg ``` --- 小技巧:在 Windos 中,你可以在資料夾中對圖片按右鍵,選擇"內容"後選擇"詳細資料",接著你可以看到圖片大小(像素)、資料夾路徑等資訊 ![image](https://hackmd.io/_uploads/rkE9mnMMxx.png) ## 運作邏輯 OpenCV 的核心概念 OpenCV 的運作核心在於將圖像和影片視為 數值陣列,透過 NumPy 進行高效處理。這就像把圖片當成一個巨大的數字表格,每個格子存著像素資訊。理解這個邏輯,您就能輕鬆掌握 OpenCV 的魔法! ### 圖像如何表示? 在 OpenCV 中,圖像是以 NumPy 陣列儲存的,具體形式取決於圖像類型: #### 彩色圖像(BGR 格式) 三維陣列,形狀為 (高度, 寬度, 3),其中 3 代表藍(B)、綠(G)、紅(R)三個通道。每個像素是一個 [B, G, R] 數值組合,例如 `[255, 0, 0]` 表示純藍。 #### 灰階圖像 二維陣列,形狀為 (高度, 寬度),每個像素只有單一亮度值(0 到 255,0 為黑,255 為白)。 #### 影片 一堆圖像(每一張稱為幀),按時間順序排列,像一本快速翻動的圖畫書。 假設一張 2x2 的彩色圖像,其陣列可能如下: ``` [ [[255, 0, 0], [0, 255, 0]], # 第一行:藍色像素、綠色像素 [[0, 0, 255], [100, 100, 100]] # 第二行:紅色像素、灰色像素 ] ``` 灰階版本則是: ``` [ [200, 150], # 第一行亮度值 [100, 50] # 第二行亮度值 ] ``` ### `img.shape` `img.shape` 是 NumPy 陣列的屬性,用來查看圖像的尺寸和通道數,返回一個 tuple: 彩色圖像:(高度, 寬度, 3),例如 (1080, 1920, 3) 表示 1080 像素高、1920 像素寬的彩色圖。 灰階圖像:(高度, 寬度),例如 (1080, 1920)。 如果圖片未載入,則會報錯(需檢查 img is None)。 範例:檢查圖像形狀: ``` import cv2 image = cv2.imread('image.jpg') if image is None: print("錯誤:圖片沒讀到!") else: print(image.shape) ``` 假設圖片是 1920x1080 的彩色圖,輸出會是:`(1080, 1920, 3)` 可以把 `img.shape`想像成可以告訴你圖片規格的函數: ``` +--------------------+ ← 寬度 (1920 像素) | | | | ↑ 高度 (1080 像素) | | × 3 (BGR 通道) +--------------------+ ``` ## 圖片轉化以及範例程式碼 OpenCV 的圖像處理本質上是對 NumPy 陣列的操作。您可以直接修改像素值,或使用內建函式進行轉換。常見轉化包括: 色彩轉換:例如從 BGR 轉灰階,用 cv2.cvtColor() 將三維陣列壓縮成二維,去掉色彩只留亮度。 縮放:用 `cv2.resize()` 改變陣列尺寸,例如把 (1080, 1920) 縮到 (300, 300)。 旋轉:用 `cv2.rotate()` 重新排列像素,例如順時針 90 度會交換高度和寬度。 切割:用陣列切片提取部分區域,例如只取左上角。 ### 切割圖片 切割圖片是直接操作 NumPy 陣列的子集,使用 `[y1:y2, x1:x2]` 語法提取指定區域。`y1:y2` 選取高度範圍,`x1:x2` 選取寬度範圍。 範例:切割圖片的左上四分之一: ``` import cv2 image = cv2.imread('image.jpg') if image is None: print("錯誤:圖片沒讀到!") else: height, width = image.shape[0:2] # 取得高度和寬度 cropped_image = image[0:height//2, 0:width//2] # 切割左上角 cv2.imshow('切割後', cropped_image) cv2.waitKey(0) cv2.destroyAllWindows() ``` 假設原圖是 1000x1000,切割後是 500x500: ``` +-----------------------+ | [保留區域] | | ← (0:500, 0:500) |-----------+-----------| | | | +-----------------------+ 切割後: +---------+ | 500x500 | ← 只保留左上角區域 +---------+ ``` 注意:確保 `y1:y2` 和 `x1:x2` 不超過圖像邊界,否則會報錯。 --- ## 常見函數語法 以下是 OpenCV 的核心函數,以及一些簡單範例: cv2.imread() 功能:讀取圖像。語法: image = cv2.imread('檔案路徑', 模式) 範例: image = cv2.imread('image.jpg') cv2.imshow() 功能:顯示圖像。語法: cv2.imshow('視窗名稱', 圖像) 範例: cv2.imshow('圖像', image) cv2.waitKey(0) cv2.destroyAllWindows() cv2.imwrite() 功能:儲存圖像。語法: cv2.imwrite('新檔案名稱', 圖像) 範例: cv2.imwrite('saved_image.jpg', image) cv2.resize() 功能:調整圖像大小。語法: resized_image = cv2.resize(圖像, (寬度, 高度)) 範例: resized_image = cv2.resize(image, (300, 300)) cv2.cvtColor() 功能:轉換色彩空間。語法: converted_image = cv2.cvtColor(圖像, 轉換代碼) 範例: gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) cv2.rectangle() 功能:繪製矩形。語法: cv2.rectangle(圖像, (x1, y1), (x2, y2), 顏色, 粗細) 範例: cv2.rectangle(image, (100, 100), (200, 200), (0, 0, 255), 2) cv2.VideoCapture() 功能:開啟影片或攝影機。語法: cap = cv2.VideoCapture(來源) 範例: cap = cv2.VideoCapture('video.mp4') 圖像操作 以下是實用的圖像處理範例,結合上述函數。 讀取、顯示與儲存 範例:讀取、顯示並儲存圖片: import cv2 image = cv2.imread('image.jpg') if image is None: print("錯誤:圖片沒讀到!") else: cv2.imshow('圖像', image) cv2.waitKey(0) cv2.imwrite('saved_image.jpg', image) cv2.destroyAllWindows() 縮放與色彩轉換 範例:轉灰階並縮放: gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) resized_image = cv2.resize(gray_image, (300, 300)) cv2.imshow('灰階縮放', resized_image) cv2.waitKey(0) cv2.destroyAllWindows() 切割圖片 範例:切割左上角: height, width = image.shape[:2] cropped_image = image[0:height//2, 0:width//2] cv2.imshow('切割後', cropped_image) cv2.waitKey(0) cv2.destroyAllWindows() 播放影片 範例:播放影片,按 'q' 退出: cap = cv2.VideoCapture('video.mp4') while True: ret, frame = cap.read() if not ret: break cv2.imshow('影片', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows() 學完之後 您現在應該對 OpenCV 的基礎有了扎實理解!這些技能是電腦視覺的敲門磚,後續可進階到人臉辨識或物件追蹤。想深入學習?試試這些資源: OpenCV 官方文件({%preview https://docs.opencv.org/%}):函式詳細說明。 LearnOpenCV({%preview https://learnopencv.com/%}):實用教學。 PyImageSearch({%preview https://pyimagesearch.com/%}):進階應用。 動手做個小專案吧,例如把照片轉成卡通風,或從影片抓出特定畫面。OpenCV 的世界等您探索!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password
    or
    Sign in via Google Sign in via Facebook Sign in via X(Twitter) Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    By signing in, you agree to our terms of service.

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully