zoukankan      html  css  js  c++  java
  • 1.3 应用结合1.1 和1.2 处理某个文件夹'Icons-dp'下所有PNG-把PNG文件透明边白色,然后沿有效图形剪切

    原理:参考1.1和1.2

    import cv2
    import os
    import numpy as np
    
    
    def alpha2white_opencv2(img):
        sp = img.shape
        width = sp[0]
        height = sp[1]
        for yh in range(height):
            for xw in range(width):
                color_d = img[xw, yh]
                if color_d[3] != 255:  # 找到alpha通道不為255的像素
                    img[xw, yh] = [255, 255, 255, 255]  # 改變這個像素
        return img
    
    
    def cut_img(img, full_file_path_to_save):
        loc = np.where(img < 255)  # 内容为非白色部分(有意义部分)
        lx = []
        ly = []
        for pt in zip(*loc[::-1]):  # pt 为每个像素点的坐标
            lx.append(pt[1])
            ly.append(pt[2])
        sx = min(lx)
        bx = max(lx)
        sy = min(ly)
        by = max(ly)
        cv2.imwrite(full_file_path_to_save, img[sy:by, sx:bx])  # 保存时只保留有意义部分
    
    
    if __name__ == '__main__':
    
        filePath = 'Icons-dp/'
        file_name_list = []
        for i, j, k in os.walk(filePath):
            file_name_list = k
        for file in file_name_list:
            full_file_path = filePath + file
            image = cv2.imread(full_file_path, cv2.IMREAD_UNCHANGED)  # 第二个参数保留Alpha通道
            image = alpha2white_opencv2(image)
            cut_img(image, 'd' + full_file_path)  # 確認路徑'dIcons-dp' 存在,如不存在程序不會報錯也不會寫入圖片
  • 相关阅读:
    Corn Fields
    状压DP
    全排列函数
    搜索
    前缀和与差分
    最小花费
    【Lintcode】062.Search in Rotated Sorted Array
    【LeetCode】039. Combination Sum
    【LeetCode】040. Combination Sum II
    【LeetCode】047. Permutations II
  • 原文地址:https://www.cnblogs.com/askayoyoo/p/11590457.html
Copyright © 2011-2022 走看看