Sam Yang
    • 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

      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.
      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
    • Engagement control
    • 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 Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control 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

    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.
    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
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 用python搞點事 - 自製圖片轉txt小工具 tags: sirla, python, workshop --- > [TOC] > > 參考資料: [Python趣味实用小工具](http://www.demodashi.com/demo/12918.html) # 主題一 - 自製圖片轉txt小工具 :::info 需具備能力: 了解python基礎語法 能學到甚麼: 使用PIL套件處理圖片、檔案讀寫 使用軟體: python3、PIL、Notepad++ ::: ## 何謂套件 套件是別人寫好的工具,我們可以用這些工具提供給我們的api(application programming interface)來完成我們想做的事情。 ## PIL套件介紹 PIL(Python Image Library)是一套處理圖片的套件,他可以調整圖片的大小、亮度、對比、色調、裁切圖片、旋轉圖片、加濾鏡、附加文字......等等,雖然沒有專業的圖像編輯軟體來的強大,但可以批次處理圖片,而且彈性較大。 ## 圖片檔概念 圖像檔案保存的方式是這樣的,假設有一張200x100的圖片檔,顏色編碼為RGB,這是什麼意思呢? 200x100指的是像素,這張圖片的寬有200個像素、高有100,也就是說這張圖片總共有20000個像素 那每個像素究竟存了什麼值? 這邊看到RGB,代表每個像素存取的是RGB三個顏色的值,每個顏色一個Byte(8bit) ## 設計想法 * 目標: 製作一個圖片轉成文字檔的小工具 * 核心流程: 將圖片轉為黑白,讀取每個像素,是黑的就填上@符號,是白的就填上_符號 ## 實作 :::info 完整程式碼: 在開始之前先確定電腦有裝好python3、pip、Notepad++ notepad++載點: https://notepad-plus-plus.org/download/v7.6.6.htmlNotepad++ 選這個zip package 32-bit x86 ::: 1. 安裝並引入PIL套件 使用pip(python的套件管理系統)進行安裝,這邊注意要用pillow作為名稱 ```bash= C:\Users\Sam> pip install pillow ``` 在python檔案開頭使用這行程式碼可將PIL當中的Image模組引入 ```python= from PIL import Image ``` 2. 開啟圖片 ```python= img = Image.open(imgName) ``` 3. 顯示圖片資訊,如果色彩模式不是RGB則轉換為RGB ```python= print("圖片資訊: 大小為{}x{}, 格式為{}, 色彩模式為{}".format(img.size[0], img.size[1], img.format, img.mode)) if img.mode != 'RGB': print("圖片顏色編碼不是RGB,進行轉換") img = img.convert('RGB') print("轉換完成") ``` * img.size是一個紀錄圖片大小的tuple,img.size[0]是寬、img.size[1]是高 * img.mode是一個字串,紀錄圖片的編碼,常見的有這些 * RGB: 三色,R紅、G綠、B藍(3x8bits) * RGBA: 跟RGB一樣,只是多了Alpha值,也就是透明度(4x8bits) * CMYK: 四色,C青、M洋紅、Y黃、K黑色(4x8bits) * 1: 黑白(1bit) * L: 256色灰階(8bits) * P: 256色彩色(8bits) > 參考: https://pillow.readthedocs.io/en/3.1.x/handbook/concepts.html#modes 4. 調整圖片大小 ```python= zoom = 0 # 縮小比率 if width >= maxSize: zoom = width / maxSize width = int(width / zoom) height = int(height / zoom) height = int(height / 2) # 除2讓比例看起來比較正確 img = img.resize((width, height)) print("圖片寬於{},已縮小為{}x{}".format(maxSize, img.size[0], img.size[1])) ``` 5. 將圖片轉為黑白 ```python= img = img.convert('1') ``` 6. 開啟文字文件 ```python= txt = open(namestr, 'w') ``` 7. 從上至下、從左至右讀取每個pixel的值 轉換成黑白顏色編碼後,每個pixel的值,不是1就是0,我們從上而下、由左而右讀取每個pixel,如果是1則在文字檔中寫入@代表黑色部分,如果是0則寫入_代表白色部分。 ```python= for y in range(height): for x in range(width): pixel = img.getpixel((x, y)) # print('x= ', x, 'y= ', y, 'pixel= ', pixel) if pixel != 0: txt.write('_') else: txt.write('@') txt.write('\n') ``` 8. 關閉文字文件 ```python= txt.close() ```

    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

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    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