修改图片颜色小工具V1.2

Changelog

2023年1月20日13:57:37

  1. 增加去背景功能,可以保存成透明背景的png格式。
  2. 排版的代码从grid改为place方式。
  3. 增加menubar,帮助。
  4. 整理部分代码结构,减少了函数传参,采用字典方式。

功能介绍

开始界面.png
取色后自动输入.png
预览变成新窗口.png

选择一张图片,然后输入希望改变哪种颜色的色号,然后输入希望变成新颜色的色号。然后点击提交,就可以完成图片预览和保存功能。此功能和PS里面的魔术棒功能差不多。
注:此功能也有色差的选择,目前默认是30色差。后续再优化一下,色差也尽量可输入。

工具下载

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

源码展示

由于非科班出身,而且只是闲来无聊随便写写,所以代码漏洞比较多。也不打算继续优化代码。

#encoding=utf-8

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 helpYou():
    tkinter.messagebox.showinfo("帮助", "就是一个PS工具,没那么难用,自己摸索一下!")
    pass

def removeBackgroundColor():
    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
    cv.imshow('result', result)
    print(type(result))
    print(result)
    cv.imwrite('result.png', result, [int(cv.IMWRITE_PNG_COMPRESSION), 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'])

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
    temp = image[result_dict['posY'], result_dict['posX']]  #把坐标对应的颜色值获取到
    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()

def changeColor(chromaticAberration):

    image = cv.imdecode(np.fromfile(result_dict['file_path'], dtype=np.uint8), -1)

    h = image.shape[0]  ## 图像高度
    w = image.shape[1]  ## 图像宽度

    result_dict['picHeight'] = h
    result_dict['picWidth'] = w

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

    for j in range(0,w):
        for i in range(0,h):
            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])
    return image

def getOldColorInputToInt():
    result_dict['oldG'] = int(inputG.get())
    result_dict['oldB'] = int(inputB.get())
    result_dict['oldR'] = int(inputR.get())

def getNewColorInputToInt():
    result_dict['newG'] = int(inputG2.get())
    result_dict['newB'] = int(inputB2.get())
    result_dict['newR'] = int(inputR2.get())

def showChangeColor():
    btnSavePic['state']=tkinter.NORMAL
    image = changeColor(30)
    cv.imshow("img2",image)

def saveChangeColor():
    image = changeColor(30)
    cv.imwrite("change1.png", image)
    btnSavePic['state'] = tkinter.DISABLED

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

    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)

if __name__ == '__main__':

    result_dict = {'file_path':"123",'posX':"0",'posY':"0",
                   'picWidth':"0",'picHeight':"0",
                   'oldR':256,'oldG':256,'oldB':256,
                   'newR':256,'newG':256,'newB':256} #用来存储函数中需返回的值

    root=tkinter.Tk()
    root.minsize(800,600)
    root.maxsize(1900,1000)
    root.title("选图换颜色V1.2")

    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)
    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)
    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)
    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)
    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)
    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)
    inputB2.place(x=350,y=100)

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

    btnPickColor=tkinter.Button(root,text='选取色号',command=funPickColor) #生成button
    btnPickColor.place(x=20,y=150)

    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)
    btnSavePic['state']=tkinter.DISABLED

    btnRemveBG = tkinter.Button(root, text='去除该颜色', command=removeBackgroundColor)  # 生成button
    btnRemveBG.place(x=350, y=150)
    # btnRemveBG['state'] = tkinter.DISABLED

    root.mainloop()

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容