python小程式實作Pic2Icon轉換
文章目錄
- python小程式實作Pic2Icon轉換
- 前言
- 一、程式使用步驟
- 1.雙擊打開程式,等待命令列彈出提示資訊,
- 2.將所要轉換的圖片的檔案拖入命令框后按下回車,等待程式執行完畢,
- 3.程式會將icon圖示輸出到圖片所在目錄的Output_Icon檔案夾下,
- 二、代碼說明
- 源代碼展示
- 1.匯入庫
- 2.定義類Picture和類操作
- 三、撰寫經歷
- 可優化
前言
該程式用來將普通格式的圖片轉換成*.ico系統可用圖示檔案,你可以將轉換出的圖示用于設定檔案夾圖示、快捷方式圖示、程式圖示等其他用途,
做程式的貧訓是前兩天在用pipinstaller做python軟體的時候發現一個小問題,
pipinstaller命令有一個引數:-i +icon圖片路徑
可以指定打包制成的*.exe系統執行檔案的圖示顯示,但是這個icon圖片的格式只能是*.ico,如果需要自定義一張圖片作為程式的圖示,可能就需要自己找圖片轉icon的網站進行轉換,度娘提供的前幾個網站著實不太行,解析度、形變度感人,
于是估摸著自己寫個小程式實作圖片的轉化,
提示:
本文第一部分是軟體使用步驟的描述,軟體已經打包成可執行程式發布在Github上,不需要用戶擁有python和相關的模塊,
GitHub相關專案release鏈接
本文第二部分是代碼的說明,包括作者寫該代碼的一些經歷,因為相關的文章比較少而且有很多都過時了,所以這次的撰寫還是很費精力的,把程序寫出來也比較有趣,
一、程式使用步驟
程式下載地址https://github.com/NNUwdl/Pic2Icon/releases/tag/0.1_Version
1.雙擊打開程式,等待命令列彈出提示資訊,

2.將所要轉換的圖片的檔案拖入命令框后按下回車,等待程式執行完畢,


3.程式會將icon圖示輸出到圖片所在目錄的Output_Icon檔案夾下,

簡單介紹下如何改變檔案夾、快捷方式的圖示:1.右鍵打開檔案夾的屬性 2.打開自定義選項更改檔案夾的圖示 3.在彈出的對話框中選擇"瀏覽",選擇需要替換成的圖片,再點擊應用就可以了,

二、代碼說明
源代碼展示
1.匯入庫
這里主要用到模塊的是numpy、pillow、opencv和os:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/11/3 1:08
# @Author : Xilun Wu
# @email : nnuwxl@gmail.com
# @File : Pic2Icon.py
import os
from PIL import Image
import numpy as np
import cv2
import sys
import time
class Picture:
def __init__(self, file):
self.ext = ['jpg', 'jpeg', 'png']
self.files = [file]
self.savepath = ""
def handle_picture(self, file):
print("Converting to four channel RGBA images...")
time.sleep(0.5)
img = Image.open(file).convert('RGBA')
width = img.size[0]
height = img.size[1]
x = width / height
matrix = np.asarray(img)
print("The image resolution is being sampled at 2048x2048 size...")
time.sleep(0.5)
if width >= height:
matrix = cv2.resize(matrix, (2048, int(2048 / x)))
m = np.zeros((2048, 2048, 4), dtype=np.int)
a = int(2048 / x)
b = int((2048 - a) / 2)
for i1 in range(2048):
for i2 in range(2048):
if i1 >= b and i1 < b + a:
m[i1][i2] = m[i1][i2] + matrix[i1 - b][i2]
else:
matrix = cv2.resize(matrix, (int(x * 2048), 2048))
m = np.zeros((2048, 2048, 4), dtype=np.int)
a = int(2048 * x)
b = int((2048 - a) / 2)
for i1 in range(2048):
for i2 in range(2048):
if i2 >= b and i2 < b + a:
m[i1][i2] = m[i1][i2] + matrix[i1][i2 - b]
img = Image.fromarray(np.uint8(m), "RGBA")
print("Output image in *.ico format...")
time.sleep(0.5)
savefile0 = os.path.dirname(self.files[0])
savefile = os.path.join(savefile0, "Output_Icon")
if os.path.exists(savefile) == False:
print("Creating the output folder:{}".format(savefile))
time.sleep(1)
os.mkdir(savefile)
savepath = (self.files[0].split('\\')[-1]).split('.')[0] + ".ico"
savepath = os.path.join(savefile, savepath)
img.save(savepath, sizes=[(int(2048), int(2048))], quality=100)
print("Output complete:{}".format(savepath))
time.sleep(1)
self.savepath = savepath
def run(self):
for file in self.files:
if os.path.exists(file) == False:
print("Input image path error, please check and try again!")
print(file)
time.sleep(3)
sys.exit(0)
if file.split('.')[-1] not in self.ext:
print("Sorry, the program does not support images in this format.")
print("Surpported format: *.jpg, *.jpeg, *.png")
time.sleep(3)
sys.exit(0)
if file.split('.')[-1] in self.ext:
self.handle_picture(file)
if __name__ == "__main__":
try:
file = input("Please enter the path of the image:")
if file[0] == '\"' and file[-1] == "\"":
file = file[1:-1]
file = r"{}".format(file)
ins = Picture(file)
ins.run()
print("Opening the output Icon...")
time.sleep(0.7)
message = os.popen('\"{}\"'.format(ins.savepath))
print("The conversion has been completed, and if it fails to open,\n"
" it may be because your system does not have a default application to open the icon image.")
print("\nProcess done,\n")
except Exception as e:
print("Something went wrong:\n{}".format(e))
print("\nYou can send an error message and a screenshot of the program to the author's email for help\n")
finally:
print("Thank you for using this software.\n@Author : NNUwxl\n"
"Having additional question can email me at : nnuwxl@gmail.com")
input()
2.定義類Picture和類操作
這里類操作的步驟是
1.先把讀進來的圖片用模塊PIL.Image.convert轉化成RGBA四通道圖
2.利用函式numpy.asarray()將圖片的所有像素轉化成陣列的格式
3.利用cv2.resize()函式將上一步中得到的陣列轉化成2048x2048的陣列(可以理解為圖片重采用成了解析度2048x2048的大小)
4.當然為了保證影像不形變,空出部分用陣列[0 0 0 0]填充
5.最后用PIL.Image物件的from方法生成Image物件,然后用Image物件的save方法保存icon
class Picture:
def __init__(self, file):
self.ext = ['jpg', 'jpeg', 'png']
self.files = [file]
self.savepath = ""
def handle_picture(self, file):
print("Converting to four channel RGBA images...")
time.sleep(0.5)
img = Image.open(file).convert('RGBA')
width = img.size[0]
height = img.size[1]
x = width / height
matrix = np.asarray(img)
print("The image resolution is being sampled at 2048x2048 size...")
time.sleep(0.5)
if width >= height:
matrix = cv2.resize(matrix, (2048, int(2048 / x)))
m = np.zeros((2048, 2048, 4), dtype=np.int)
a = int(2048 / x)
b = int((2048 - a) / 2)
for i1 in range(2048):
for i2 in range(2048):
if i1 >= b and i1 < b + a:
m[i1][i2] = m[i1][i2] + matrix[i1 - b][i2]
else:
matrix = cv2.resize(matrix, (int(x * 2048), 2048))
m = np.zeros((2048, 2048, 4), dtype=np.int)
a = int(2048 * x)
b = int((2048 - a) / 2)
for i1 in range(2048):
for i2 in range(2048):
if i2 >= b and i2 < b + a:
m[i1][i2] = m[i1][i2] + matrix[i1][i2 - b]
img = Image.fromarray(np.uint8(m), "RGBA")
print("Output image in *.ico format...")
time.sleep(0.5)
savefile0 = os.path.dirname(self.files[0])
savefile = os.path.join(savefile0, "Output_Icon")
if os.path.exists(savefile) == False:
print("Creating the output folder:{}".format(savefile))
time.sleep(1)
os.mkdir(savefile)
savepath = (self.files[0].split('\\')[-1]).split('.')[0] + ".ico"
savepath = os.path.join(savefile, savepath)
img.save(savepath, sizes=[(int(2048), int(2048))], quality=100)
print("Output complete:{}".format(savepath))
time.sleep(1)
self.savepath = savepath
三、撰寫經歷
博主一開始接觸的python關于影像處理的模塊是opencv(cv2),所以一開始是想要利用opencv庫完成代碼的撰寫,
因為對opencv模塊有一定的了解,所以,很快啊,cv2.imread()、cv2.imwrite()代碼初步就寫完了,
眾所周知這兩個函式對于中文路徑的識別會出現問題,所以要添加如下代碼,并用其中函式替代:
# 讀取影像,解決imread不能讀取中文路徑的問題, 回傳RGB影像
def cv_imread(filePath):
cv_img = cv2.imdecode(np.fromfile(filePath, dtype=np.uint8), -1) # BGR
## imdecode讀取的是rgb,如果后續需要opencv處理的話,需要轉換成bgr,轉換后圖片顏色會變化
# cv_img=cv2.cvtColor(cv_img,cv2.COLOR_RGB2BGR) # RGB
return cv_img
# 讀取影像,解決imwrite不能讀取中文路徑的問題
def cv_imwrite(filePath, inputimg):
cv_img = cv2.imencode(".ico", inputimg)[1].tofile(filePath)
return cv_img
接下來遇到的問題就是opencv模塊并不支持*.ico格式的圖片輸出,
在網上查閱相關資料發現*.ico圖片格式其實和*.bmp圖片格式是一樣的,只要將*.bmp圖片的后綴名改為.ico就可以將圖片轉化為可供windows使用的icon圖示,
于是題主就使用opencv庫將圖片轉化為bmp格式,再用os庫rename函式,將輸出的bmp重命名成.ico,這樣輸出的圖示雖然可以用圖片瀏覽器打開,但是在設定為檔案夾圖示的時候會有各種各樣的顯示問題,個人猜測可能是由于icon圖示的解析度都是16x16、256x256這樣的正方形,如果圖片是非正方形就會出現顯示問題,
于是利用cv2.resize函式將cv2.imread讀出的影像陣列轉化為正方形陣列,再進行輸出,
但是這樣得到的圖片會有拉伸形變問題,如果我不想要拉伸圖片理應將擴充的像素塊設定成透明,這樣就需要圖片擁有四通道’RGBA’,而簡單翻閱opencv檔案博主發現imwrite并不支持輸出四通道圖片,

唔,這么看來opencv庫屬實不太行,上次想用它實作對視頻中音頻的提取,最后發現人家只支持對視頻中的影像進行處理,壓根就沒在意對視頻中的音頻進行處理;這次又是它不支持對四通道圖片的輸出,
滿滿的絕望,
無奈之下咱們換庫,opencv模塊不行咱用pillow.
pillow的Image.convert(‘RGBA’)可以將圖片轉化成四通道物件;
pillow的Image.size可以回傳圖片的解析度陣列;
pillow的Image.fromarray可以從陣列讀取成Image物件;
pillow的Image.save 可以直接保存*.ico圖示檔案;
opencv模塊,不行,pillow模塊,行!👍
于是就利用pillow讀取圖片并轉化成四通道,numpy.asarray()讀取成陣列,cv2.resize()擴充成想要的解析度,將空缺部分用array[0 0 0 0]替代,最后再用Image.save進行輸出,

但是就是在最后一步的輸出發生了問題,輸出icon的解析度始終只用16x16,這圖能看?

于是只能吭哧吭哧去讀pillow的檔案Pillow官方檔案

好家伙,還需要我指定一個size,最大還不能超過256x256,行吧,先輸出試試

這樣終于能夠輸出256x256的圖示了,

有沒有發現256x256的解析度根本不夠看,特別是在作為檔案夾icon的時候,一張圖能給你糊成馬賽克,可是pillow庫最大只支持256x256怎么辦?
博主嘗試修改pillow的輪子看看能不能突破限制,
找到Image.save中控制icon輸出的代碼部分:

好家伙,它真給限制成256x256的了,
但是沒有關西,我們這里給它稍微改一改:

然后嘗試輸出一下:

成了!👍
好家伙,我直接好家伙,你這塊代碼擱這虛空擋拆呢,明明沒有限制你偏要人為加一手限制,
不知道的還以為你要出付費DLC后續解鎖呢🙊
但是就這解析度對于更精細的圖肯定還是不夠的用,于是我們直接上2048x2048:


終于舒服了,
可優化
還有一些問題等待解決, 比如可以使用python的視窗模塊讓用戶界面更友好,比如將圖片重采樣成2048x2048時運用的是cv2.resize函式將陣列擴充,個人發現這樣的方法會增加圖片的銳度,因為它好像并不會改變陣列的值,比如說重采樣的點在原圖中位于兩個顏色的交界處,那它其實應該取中間色,但是resize函式并沒有這樣做,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/204807.html
標籤:其他
上一篇:cgb2007-京淘day06
