Python將圖片背景透明化


def transparent_background(path):
    try:
        img = Image.open(path)
        img = img.convert("RGBA")  # 轉換獲取信息
        pixdata = img.load()
        color_no = get_convert_middle(path) + 30  # 摳圖的容錯值

        for y in range(img.size[1]):
            for x in range(img.size[0]):
                if pixdata[x, y][0] > color_no and pixdata[x, y][1] > color_no and pixdata[x, y][2] > color_no and \
                        pixdata[x, y][3] > color_no:
                    pixdata[x, y] = (255, 255, 255, 0)

        if not path.endswith('png'):
            os.remove(path)
            replace_path_list = path.split('.')
            replace_path_list = replace_path_list[:-1]
            path = '.'.join(replace_path_list) + '.png'

        img.save(path)
        img.close()
    except Exception as e:
        return Falsereturn path


def get_convert_middle(img_path):
    I = Image.open(img_path)
    L = I.convert('L')
    im = numpy.array(L)
    im4 = 255.0 * (im / 255.0) ** 2  # 對圖像的像素值求平方后得到的圖像
    middle = (int(im4.min()) + int(im4.max())) / 2
    return middle

# 調用 transparent_background, 傳入圖片路徑, 該方法把圖片修改后替換了源文件

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM