修改圖片顏色小工具V1.3

工具更健壯,更新日志后續(xù)再補充,源碼已復(fù)制更新至V1.3车摄!

Changelog

2023年1月20日13:57:37

  1. 增加去背景功能粟誓,可以保存成透明背景的png格式奏寨。
  2. 排版的代碼從grid改為place方式。
  3. 增加menubar鹰服,幫助病瞳。
  4. 整理部分代碼結(jié)構(gòu),減少了函數(shù)傳參悲酷,采用字典方式套菜。

功能介紹

開始界面.png
取色后自動輸入.png
預(yù)覽變成新窗口.png

選擇一張圖片,然后輸入希望改變哪種顏色的色號设易,然后輸入希望變成新顏色的色號逗柴。然后點擊提交,就可以完成圖片預(yù)覽和保存功能亡嫌。此功能和PS里面的魔術(shù)棒功能差不多嚎于。
注:此功能也有色差的選擇掘而,目前默認是30色差。后續(xù)再優(yōu)化一下于购,色差也盡量可輸入袍睡。

工具下載

https://www.jianguoyun.com/p/DaggDTQQ4MGKChiOzvIEIAA

源碼展示

由于非科班出身,而且只是閑來無聊隨便寫寫肋僧,所以代碼漏洞比較多斑胜。也不打算繼續(xù)優(yōu)化代碼。

#encoding=utf-8
import time

import cv2 as cv
import numpy as np
import tkinter
import tkinter.messagebox
from tkinter.filedialog import asksaveasfilename
from tkinter import END
import PIL
from PIL import Image,ImageTk


def test(content):
    # 實時驗證輸入框是否只為數(shù)字嫌吠!
    return content.isdigit()

def helpYou():
    tkinter.messagebox.showinfo("幫助", "就是一個PS工具止潘,沒那么難用,自己摸索一下辫诅!")
    pass

def inputIsOk():
    getOldColorInputToInt()
    getNewColorInputToInt()
    oldColor = (result_dict['oldG'], result_dict['oldB'], result_dict['oldR'])
    newColor = (result_dict['newB'], result_dict['newG'], result_dict['newR'])

    if max(oldColor,newColor)>255 or min(oldColor,newColor)<0:
        tkinter.messagebox.showinfo("提示","輸入范圍:0-255凭戴!")
        return False
    else:
        return True

def removeBackgroundColor():
    global gl_imgtemp
    if max(result_dict['oldG'],result_dict['oldB'],result_dict['oldR']) > 255:
        tkinter.messagebox.showinfo("提示","當前輸入框數(shù)值不是0-255 !")
    else:
        getOldColorInputToInt()

        img = cv.imdecode(np.fromfile(result_dict['file_path'], dtype=np.uint8), -1)
        result = cv.cvtColor(img, cv.COLOR_BGR2BGRA)
        for i in range(0, img.shape[0]):  # 訪問所有行
            for j in range(0, img.shape[1]):  # 訪問所有列
                if img[i, j, 0] == result_dict['oldB'] and img[i, j, 1] == result_dict['oldG'] and img[i, j, 2] == result_dict['oldR']:
                    result[i, j, 3] = 0
        print(type(result))
        cv.imwrite('result.png', result)

        removeBGWindow = tkinter.Toplevel()
        removeBGWindow.minsize(img.shape[1], img.shape[0])
        removeBGWindow.maxsize(img.shape[1], img.shape[0])
        removeBGWindow.title("去掉背景預(yù)覽")

        photo = PIL.ImageTk.PhotoImage(Image.open('result.png'))
        labelDisplayPic2 = tkinter.Label(removeBGWindow, image=photo)  # 生成標簽并將標簽添加到主窗口
        labelDisplayPic2.image = photo
        labelDisplayPic2.place(x=0, y=0)



def mouse_click(event, x, y, flags, para):
    if event == cv.EVENT_LBUTTONDOWN:  # 左邊鼠標點擊
        result_dict['posX']=x
        result_dict['posY'] = y #將點選的坐標輸出炕矮,這里的坐標是相對圖像窗口的坐標么夫,所以可以以此來獲取顏色值。
        # print('PIX:', result_dict['posX'], result_dict['posY'])
    else:
        pass

def funPickColor():
    image = cv.imdecode(np.fromfile(result_dict['file_path'], dtype=np.uint8), -1)
    cv.namedWindow("click anykey to exit")
    cv.setMouseCallback("click anykey to exit", mouse_click)
    while True:
        cv.imshow('click anykey to exit', image)
        if cv.waitKey() != ord('q'):
            break
    try:
        temp = image[result_dict['posY'], result_dict['posX']]  #把坐標對應(yīng)的顏色值獲取到
        temp = temp[::-1]   #獲取的顏色值是BGR的肤视,所以需要做倒序處理档痪。
        temp=list(temp)
        # 先清空輸入框
        inputR.delete(0,END)
        inputG.delete(0, END)
        inputB.delete(0, END)
        # 再載入輸入框的值
        inputR.insert(0,str(temp[0]))
        inputG.insert(0, str(temp[1]))
        inputB.insert(0, str(temp[2]))

        getOldColorInputToInt()

        cv.destroyAllWindows()
    except:
        tkinter.messagebox.showinfo("提示","未點選圖像中的像素!")

def changeColor():
    global gl_imgtemp
    image = cv.imdecode(np.fromfile(result_dict['file_path'], dtype=np.uint8), -1)
    result_dict['picHeight'] = image.shape[0]  ## 圖像高度
    result_dict['picWidth'] = image.shape[1]  ## 圖像寬度
    chromaticAberration = result_dict['chromaticAberration']
    oldColor = (result_dict['oldG'], result_dict['oldB'], result_dict['oldR'])
    newColor = (result_dict['newB'], result_dict['newG'], result_dict['newR'])

    for j in range(0,result_dict['picWidth']):
        for i in range(0,result_dict['picHeight']):
            a = image.item(i,j,0)
            b = image.item(i,j,1)
            c = image.item(i,j,2)

            ifa = False
            ifb = False
            ifc = False

            if a >=oldColor[0]-chromaticAberration and a <= oldColor[0]+chromaticAberration:
                ifa = True

            if b >=oldColor[1]-chromaticAberration and b <= oldColor[1]+chromaticAberration:
                ifb = True

            if c >=oldColor[2]-chromaticAberration and c <= oldColor[2]+chromaticAberration:
                ifc = True

            if ifa and ifb and ifc:
                image.itemset((i, j, 0),newColor[0])
                image.itemset((i, j, 1), newColor[1])
                image.itemset((i, j, 2), newColor[2])
    gl_imgtemp = image
    result_dict['picExist']=True

def getOldColorInputToInt():
    try:
        result_dict['oldG'] = int(inputG.get())
        result_dict['oldB'] = int(inputB.get())
        result_dict['oldR'] = int(inputR.get())
    except:
        tkinter.messagebox.showinfo("提示","原顏色輸入值不合理邢滑!")

def getNewColorInputToInt():
    try:
        result_dict['newG'] = int(inputG2.get())
        result_dict['newB'] = int(inputB2.get())
        result_dict['newR'] = int(inputR2.get())
    except:
        tkinter.messagebox.showinfo("提示","新顏色輸入值不合理腐螟!")

def showChangeColor():
    if inputIsOk():
        changeColor()
        global gl_imgtemp
        cv.imshow("img2", gl_imgtemp)
    else:
        tkinter.messagebox.showinfo("提示","當前輸入框數(shù)值不是0-255 !")

def saveChangeColor():
    if result_dict['picExist']:
        global gl_imgtemp
        cv.imwrite('change1.png', gl_imgtemp)
    else:
        tkinter.messagebox.showinfo("提示","當前沒有生成圖片困后!")

def funOpenFile():
    picName = tkinter.filedialog.askopenfilename()
    result_dict['file_path'] = picName  # 把結(jié)果放在字典里乐纸,作用相當于 return
    # labelDisplayFileName.text(result_dict['file_path'])
    labelDisplayFileName.configure(text=result_dict['file_path'])

    try:
        photo = PIL.ImageTk.PhotoImage(Image.open(picName))
        # print(type(photo))
        labelDisplayPic = tkinter.Label(root,image=photo)  # 生成標簽并將標簽添加到主窗口
        labelDisplayPic.image=photo
        labelDisplayPic.place(x=20,y=200)

        btnPickColor['state'] = tkinter.NORMAL
    except:
        pass

if __name__ == '__main__':

    result_dict = {'file_path':"123",'posX':"-1",'posY':"-1",
                   'picWidth':"0",'picHeight':"0",
                   'oldR':256,'oldG':256,'oldB':256,
                   'newR':256,'newG':256,'newB':256,
                   'chromaticAberration':10,
                   'picExist':False} #用來存儲函數(shù)中需返回的值

    global gl_imgtemp
    gl_imgtemp = []

    root=tkinter.Tk()
    root.minsize(800,600)
    root.maxsize(1900,1000)
    root.title("選圖換顏色V1.3")
    testCMD = root.register(test)

    file_menu = tkinter.Menu(root)
    file_menu.add_command(label="幫助",command=helpYou)
    root.config(menu=file_menu)

    openFile = tkinter.Button(root,text='選擇圖片文件',command=funOpenFile) #生成button
    openFile.place(x=20,y=20)         #將button添加到root主窗口
    labelDisplayFileName=tkinter.Label(root,text='請選擇圖片文件:') #生成標簽并將標簽添加到主窗口
    labelDisplayFileName.place(x=150,y=20)

    ##################################################################
    # 展示希望替換的顏色色號
    label1=tkinter.Label(root,text='原顏色色號:') #生成標簽并將標簽添加到主窗口
    label1.place(x=20,y=70)

    labelR=tkinter.Label(root,text='R:',width=5) #生成標簽并將標簽添加到主窗口
    labelR.place(x=100,y=70)
    inputR=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputR.place(x=150,y=70)

    labelG=tkinter.Label(root,text='G:',width=5) #生成標簽并將標簽添加到主窗口
    labelG.place(x=200,y=70)
    inputG=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputG.place(x=250,y=70)

    labelB=tkinter.Label(root,text='B:',width=5) #生成標簽并將標簽添加到主窗口
    labelB.place(x=300,y=70)
    inputB=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputB.place(x=350,y=70)

    ################################################################
    # 展示希望新顏色色號
    label2=tkinter.Label(root,text='新顏色的色號:') #生成標簽并將標簽添加到主窗口
    label2.place(x=20,y=100)

    labelR2=tkinter.Label(root,text='R:',width=5) #生成標簽并將標簽添加到主窗口
    labelR2.place(x=100,y=100)
    inputR2=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputR2.place(x=150,y=100)

    labelG2=tkinter.Label(root,text='G:',width=5) #生成標簽并將標簽添加到主窗口
    labelG2.place(x=200,y=100)
    inputG2=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputG2.place(x=250,y=100)

    labelB2=tkinter.Label(root,text='B:',width=5) #生成標簽并將標簽添加到主窗口
    labelB2.place(x=300,y=100)
    inputB2=tkinter.Entry(root,width=5, validate='key',validatecommand=(testCMD,'%P'))
    inputB2.place(x=350,y=100)



    ############################################

    btnPickColor=tkinter.Button(root,text='選取色號',command=funPickColor) #生成button
    btnPickColor.place(x=20,y=150)
    btnPickColor['state'] = tkinter.DISABLED

    button1=tkinter.Button(root,text='提交修改',command=showChangeColor) #生成button
    button1.place(x=150,y=150)

    btnSavePic=tkinter.Button(root,text='保存修改圖',command=saveChangeColor) #生成button
    btnSavePic.place(x=250,y=150)

    btnRemveBG = tkinter.Button(root, text='去除該顏色', command=removeBackgroundColor)  # 生成button
    btnRemveBG.place(x=350, y=150)

    root.mainloop()


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市操灿,隨后出現(xiàn)的幾起案子锯仪,更是在濱河造成了極大的恐慌,老刑警劉巖趾盐,帶你破解...
    沈念sama閱讀 221,695評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件庶喜,死亡現(xiàn)場離奇詭異,居然都是意外死亡救鲤,警方通過查閱死者的電腦和手機久窟,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,569評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來本缠,“玉大人斥扛,你說我怎么就攤上這事。” “怎么了稀颁?”我有些...
    開封第一講書人閱讀 168,130評論 0 360
  • 文/不壞的土叔 我叫張陵芬失,是天一觀的道長。 經(jīng)常有香客問我匾灶,道長棱烂,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,648評論 1 297
  • 正文 為了忘掉前任阶女,我火速辦了婚禮颊糜,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘秃踩。我一直安慰自己衬鱼,他們只是感情好,可當我...
    茶點故事閱讀 68,655評論 6 397
  • 文/花漫 我一把揭開白布憔杨。 她就那樣靜靜地躺著鸟赫,像睡著了一般。 火紅的嫁衣襯著肌膚如雪芍秆。 梳的紋絲不亂的頭發(fā)上惯疙,一...
    開封第一講書人閱讀 52,268評論 1 309
  • 那天,我揣著相機與錄音妖啥,去河邊找鬼。 笑死对碌,一個胖子當著我的面吹牛荆虱,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播朽们,決...
    沈念sama閱讀 40,835評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼怀读,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了骑脱?” 一聲冷哼從身側(cè)響起菜枷,我...
    開封第一講書人閱讀 39,740評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎叁丧,沒想到半個月后啤誊,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,286評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡拥娄,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,375評論 3 340
  • 正文 我和宋清朗相戀三年蚊锹,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片稚瘾。...
    茶點故事閱讀 40,505評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡牡昆,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出摊欠,到底是詐尸還是另有隱情丢烘,我是刑警寧澤柱宦,帶...
    沈念sama閱讀 36,185評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站播瞳,受9級特大地震影響掸刊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜狐史,卻給世界環(huán)境...
    茶點故事閱讀 41,873評論 3 333
  • 文/蒙蒙 一痒给、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧骏全,春花似錦苍柏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,357評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至楼咳,卻和暖如春熄捍,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背母怜。 一陣腳步聲響...
    開封第一講書人閱讀 33,466評論 1 272
  • 我被黑心中介騙來泰國打工余耽, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人苹熏。 一個月前我還...
    沈念sama閱讀 48,921評論 3 376
  • 正文 我出身青樓碟贾,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 45,515評論 2 359

推薦閱讀更多精彩內(nèi)容