Visión general
A través de Python, llevaremos a todos a binarizar la imagen en color a través de la máscara, y finalmente nos daremos cuenta de la función de estera y costura de imágenes.
Palabras clave: cap layer MASK binarized matting
Efecto de corte final:
Binarice la imagen en color a través de la máscara para realizar uniones y uniones de imágenes
Imagen binaria
import cv2
# 载入原图
img = cv2.imread('cat.jpeg')
from matplotlib import pyplot as plt
# 展示图像
plt.imshow(img[:, :, ::-1])
# 图像二值化
img_bin = cv2.inRange(img, lowerb=(9, 16, 84), upperb=(255, 251, 255))
plt.imshow(img_bin, cmap='gray')
Procesamiento de morfología matemática
# 数学形态学预处理
import numpy as np
kernel = np.ones((5,5), np.uint8)
img_bin = cv2.erode(img_bin, kernel, iterations=1)
img_bin = cv2.dilate(img_bin, kernel, iterations=2)
plt.imshow(img_bin, cmap='gray')
Filtrar dominios conectados
# 过滤掉小的contours
# 获取边缘信息
_, contours, hierarchy = cv2.findContours(image=img_bin,mode=cv2.RETR_EXTERNAL, method=cv2.CHAIN_APPROX_SIMPLE)
def contours_area(cnt):
# 计算countour的面积
(x, y, w, h) = cv2.boundingRect(cnt)
return w * h
# 获取面积最大的contour
max_cnt = max(contours, key=lambda cnt: contours_area(cnt))
# 创建空白画布
mask = np.zeros_like(img_bin)
# 获取面积最大的 contours
mask = cv2.drawContours(mask,[max_cnt],0,255,-1)
# 打印罩层
plt.imshow(mask, cmap='gray')
Recorte-binarización y operación con superposición
La operación OR / AND de img y de sí mismo (de hecho, sus resultados son los mismos) se realizan en el área de máscara (MASK). El área de cobertura es 0, negra .
La operación de binarización es si los píxeles de dos puntos img no retienen el valor original es cero, de lo contrario negro .
# 使用罩层对原来的图像进行抠图
sub_img = cv2.bitwise_or(img,img,mask=mask)
# sub_img = cv2.bitwise_and(img,img,mask=mask)
plt.imshow(sub_img[:,:,::-1])
Vaya, el gran gato blanco fue elegido, ¿no es increíble? ! ! ! !
Cambiar el color de fondo
# 给大白猫换个背景
background = np.zeros_like(img)
background[:,:,:] = (150, 198, 12)
plt.imshow(background[:,:,::-1])
# 获取新的背景
new_background = cv2.bitwise_or(background, background, mask=cv2.bitwise_not(mask))
plt.imshow(new_background[:,:,::-1])
Combinación de imágenes cv2.add
new_img = cv2.add(new_background, sub_img)
plt.imshow(new_img[:,:,::-1])
Desenfoque gaussiano
La costura es demasiado fuerte, haz un desenfoque gaussiano
# 用5*5的kernel进行高斯模糊
new_img_blur = cv2.GaussianBlur(new_img, (9,9), 5)
plt.imshow(new_img_blur[:,:,::-1])