Created
March 31, 2024 10:03
-
-
Save TomoG29/57f994b55d9bdcd887802b70c9d75ecc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
import glob | |
import os | |
import getpass | |
# パラメータ設定 | |
contrast_adjustment_value = 1.5 # コントラスト調整値 | |
chroma_key_color = np.uint8([[[0, 255, 0]]]) # クロマキー処理の指定色(緑色) | |
chroma_key_threshold = 20 # クロマキー処理の閾値 | |
noise_removal_iterations = 50 # ノイズ除去の繰り返し回数 | |
# 入出力フォルダのパス | |
import_file = os.path.join("インポートしたい画像のフォルダパス") | |
export_file = os.path.join("エクスポートしたい画像のフォルダパス") | |
def main(): | |
# 対象画像のファイルパス取得 | |
files = glob.glob(os.path.join(import_file, '*.png')) | |
# ファイルごとに処理 | |
for file in files: | |
# 画像を読み込む | |
base_image = cv2.imread(file) | |
basename = os.path.basename(file) | |
# コントラスト調整 | |
contrast_image = cv2.convertScaleAbs(base_image, alpha=contrast_adjustment_value, beta=0) | |
# クロマキー処理と二値化 | |
hsv_chroma_key_color = cv2.cvtColor(chroma_key_color, cv2.COLOR_BGR2HSV) | |
lower_green = np.array([hsv_chroma_key_color[0][0][0] - chroma_key_threshold, 50, 50]) | |
upper_green = np.array([hsv_chroma_key_color[0][0][0] + chroma_key_threshold, 255, 255]) | |
hsv_image = cv2.cvtColor(contrast_image, cv2.COLOR_BGR2HSV) | |
chromakey_image = cv2.inRange(hsv_image, lower_green, upper_green) | |
mask_image = cv2.bitwise_not(chromakey_image) | |
# ノイズ除去 | |
for _ in range(noise_removal_iterations): | |
kernel = np.ones((5, 5), np.uint8) | |
mask_image = cv2.dilate(mask_image, kernel, iterations=1) | |
mask_image = cv2.erode(mask_image, kernel, iterations=1) | |
# 元画像をマスク画像で切り抜く | |
result_image = cv2.cvtColor(base_image, cv2.COLOR_BGR2BGRA) # RGBA形式に変換 | |
result_image[:, :, 3] = mask_image # アルファチャンネルにマスク画像を設定 | |
# 画像を保存 | |
cv2.imwrite(os.path.join(export_file, 'contrast_' + basename), contrast_image) | |
cv2.imwrite(os.path.join(export_file, 'chromakey_' + basename), chromakey_image) | |
cv2.imwrite(os.path.join(export_file, 'mask_' + basename), mask_image) | |
cv2.imwrite(os.path.join(export_file, 'result_' + basename), result_image) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment