導讀 | 十字繡大家都知道吧,今天小編帶大家來玩個電子版的十字繡。用Python讀取圖片的畫素值,然後輸出到Excel表格中,最終形成一幅畫素畫,也就是電子版的十字繡了。 |
準備
既然要讀取圖片,那就需要用到 Pillow 庫,操作 Excel 需要用到 openpyxl 庫,先把這兩個庫安裝好。
$ pip3 install openpyxl $ pip3 install Pillow
色值轉換
從圖片讀取的畫素塊色值是 RGB 值,而 openpyxl 向 Excel cell 內填充顏色是十六進位制色值,因此我們們先寫一個 RGB 和十六進位制色值轉換的一個函式。
def rgb_to_hex(rgb): rgb = rgb.split(',') color = '' for i in RGB: num = int(i) color += str(hex(num))[-2:].replace('x', '0').upper() return color
圖片轉換
有了色值轉換函式,接下來要做的操作就是逐行讀取圖片的 RGB 色值,之後將 RGB 色值轉換為十六進位制色值填充到 Excel 的 cell 中即可。
def img2excel(img_path, excel_path): img_src = Image.open(img_path) # 圖片寬高 img_width = img_src.size[0] img_height = img_src.size[1] str_strlist = img_src.load() wb = openpyxl.Workbook() wb.save(excel_path) wb = openpyxl.load_workbook(excel_path) cell_width, cell_height = 1.0, 1.0 sheet = wb["Sheet"] for w in range(img_width): for h in range(img_height): data = str_strlist[w, h] color = str(data).replace("(", "").replace(")", "") color = rgb_to_hex(color) # 設定填充顏色為 color fille = PatternFill("solid", fgColor=color) sheet.cell(h + 1, w + 1).fill = fille for i in range(1, sheet.max_row + 1): sheet.row_dimensions[i].height = cell_height for i in range(1, sheet.max_column + 1): sheet.column_dimensions[get_column_letter(i)].width = cell_width wb.save(excel_path) img_src.close()
最後再來個入口函式,就大功告成啦~
if __name__ == '__main__': img_path = '/Users/xyz/Documents/tmp/03.png' excel_path = '/Users/xyz/Documents/tmp/3.xlsx' img2excel(img_path, excel_path)
驚豔時刻
激動的心,顫抖的手,來看下最終效果咋樣。
原文來自:
來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2852730/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- Python爬蟲專案100例,附原始碼!100個Python爬蟲練手例項
- Python開發實戰
- 為什麼說Python適合做大資料處理?原因竟是它!
- Python是什麼意思?Python有什麼用?
- 使用Python分析大量資料應該學些什麼?
- python實戰一個完整的專案-年終課程盤點|16 個 Python 綜合實戰專案合集
- 《Python3網路爬蟲開發實戰(第二版)》內容介紹
- 整理了70個Python實戰專案案例,教程+原始碼+筆記。從基礎到深入
- Python中的不可變集合
- 在Excel VBA中寫SQL,是一種什麼體驗
- 快過年了,用Python寫副春聯&福字送給你~
- python3網路爬蟲開發實戰_Python3 爬蟲實戰
- [Python3網路爬蟲開發實戰] Charles 的使用
- 最新版的Python寫春聯,支援行書隸書楷書,不再有缺失漢字
- 『無為則無心』Python函式 — 35、Python中的閉包
- Python的Selenium一些問題解決
- 活用Excel,成為真正的“全戰”工程師
- 《Python3 網路爬蟲開發實戰》—學習筆記
- 一款高效又省記憶體的讀寫Excel的JAVA框架