Python教程

python opencv给证件照换底色

本文主要是介绍python opencv给证件照换底色,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

昨天朋友忙要把白色背景的证件照换为红色的,比较急用,本人也不太会用PS,网上的那些转换小工具都是要收费的,就想着自己搞一搞,原理很简单,白色背景的像素值为[255,255,255],用这个信息生成mask,再将生成的Mask对应回原图像将背景区域换为红色的像素值[256,0,0]即可实现。

read image

def read_source_image(image_path):
    img = cv2.imread(image_path)
    return img

resize

def resize(img,height,whight):
    return cv2.resize(img,(whight,height))

生成mask

def generator_mask(img):
    """
    :param img: source image
    :return: mask
    """
    mask = np.zeros_like(img)
    row,col,channels = img.shape
    for i in range(row):
        for j in range(col):
            if sum(img[i, j]) == 255 * 3:
                mask[i, j] = (255, 255, 255)
            else:
                mask[i, j] = [0, 0, 0]
    # Gaussian Blur
    mask = cv2.GaussianBlur(mask, (7, 7), 0)
    return mask

白色转红色

def white_to_red(img,mask):
    """
    :param img: source image
    :param mask: mask image
    :return: red background image
    """
    img_copy = np.zeros_like(img)
    row, col, channels = img.shape
    for i in range(row):
        for j in range(col):
            if sum(mask[i,j]) != 0:
                img_copy[i,j] = [0,0,255]
            else:
                img_copy[i,j] = img[i,j]
    return img_copy

白色转蓝色

def white_to_blue(img,mask):
    """
    :param img: source image
    :param mask: mask image
    :return: Blue background image
    """
    img_copy = np.zeros_like(img)
    row, col, channels = img.shape
    for i in range(row):
        for j in range(col):
            if sum(mask[i,j]) != 0:
                img_copy[i,j] = [255,0,0]
            else:
                img_copy[i,j] = img[i,j]
    return img_copy

我自己转出来的结果还可以,但是在人的边缘位置上还是能够看到有瑕疵,所以在mask生成里面做了高斯模糊,实验验证是有用的,经过高斯模糊之后生成的图像质量改了很多,但在真用的时候还是会有一些问题,比如背景并不是纯白色的时候,分割就会有问题,后面有时间的话可以考虑用分割的方法来继续完善这个小工具。

这篇关于python opencv给证件照换底色的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!