概要
Pythonを通じて、マスクを介してカラー画像を2値化し、最終的にマットと画像のスティッチングの機能を実現します。
キーワード:キャップレイヤー マスク 2値化 マット
最終的なカットアウト効果:
マスクを通してカラー画像を2値化して、マットと画像のスティッチングを実現します
バイナリイメージ
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')
数学的形態処理
# 数学形态学预处理
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')
接続されているドメインをフィルタリングする
# 过滤掉小的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')
カットアウト2値化とオーバーレイによる操作
imgとそれ自体(実際には結果は同じ)のOR / AND演算は、マスク領域(MASK)で実行されます。カバー領域は0、黒です。
2値化操作は、2点のピクセルimgが元の値を保持しない場合はゼロ、それ以外の場合は黒になります。
# 使用罩层对原来的图像进行抠图
sub_img = cv2.bitwise_or(img,img,mask=mask)
# sub_img = cv2.bitwise_and(img,img,mask=mask)
plt.imshow(sub_img[:,:,::-1])
うわー、大きな白い猫が選ばれました。すごいですね。!!!!
背景色を変更する
# 给大白猫换个背景
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])
画像マージcv2.add
new_img = cv2.add(new_background, sub_img)
plt.imshow(new_img[:,:,::-1])
ガウスぼかし
ステッチが強すぎる、ガウスぼかしを行う
# 用5*5的kernel进行高斯模糊
new_img_blur = cv2.GaussianBlur(new_img, (9,9), 5)
plt.imshow(new_img_blur[:,:,::-1])