python PIL 和opencv检测图片是否包含透明通道

PIL检测更加准确:

from PIL import Image


def has_transparency(img):
    if img.mode == "P":
        transparent = img.info.get("transparency", -1)
        for _, index in img.getcolors():
            if index == transparent:
                return True
    elif img.mode == "RGBA":
        extrema = img.getextrema()
        if extrema[3][0] < 255:
            return True

    return False


if __name__ == "__main__":
    # extract_alpha("./13.png")
    image = Image.open("./Female_Model_Nurse.png")
    print(has_transparency(image))

opencv检测不准确:

import cv2

def alpha_to_image(alpha, image_path):
    """
    单独将 alpha 保存成图像
    :param alpha:
    :param image_path:
    :return:
    """
    cv2.imwrite(image_path, alpha)


def extract_alpha(image_path):
    """
    提取图片的 alpha 通道
    :param image_path:
    :return:
    """
    # im = cv2.imread(image_path, cv2.IMREAD_UNCHANGED)  # 顾名思义,读入完整图片,包括alpha通道
    # im = cv2.imread(image_path, cv2.IMREAD_COLOR)  # cv2.IMREAD_COLOR:默认参数,读入一副彩色图片,忽略alpha通道
    # im = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)  # cv2.IMREAD_GRAYSCALE:读入灰度图片
    im = cv2.imread(image_path)
    # 颜色空间转换?
    # if im.shape[-1] == 3:
    #     img = cv2.cvtColor(im, cv2.COLOR_BGR2BGRA)

    im_shape = im.shape
    print(f"im_shape = {im_shape}")

    # 显示图片查看
    # 显示图片查看
    cv2.imshow('imshow', im)
    cv2.waitKey(1000)
    cv2.destroyAllWindows()
    # 显示图片查看

    # # 显示图片查看

    #
    # if len(im_shape) != 4:
    #     print("此图片不包含 alpha 通道")
    # alpha = im[3]
    # # 此时获取的就是 alpha 通道
    # return alpha


if __name__ == "__main__":
    pass
    # print(extract_alpha('./11.png'))
    # print(extract_alpha('./bb.png'))
    print(extract_alpha('./Female_Model_Nurse.png'))

你可能感兴趣的:(图像/音频/视频处理,opencv,python,计算机视觉,PIL)