import cv2
import numpy as np
import os
##--- 指定フォルダ内のPNGファイルリスト取得
def get_png_files(dir_path):
"""指定されたディレクトリ内のすべてのPNGファイルを取得します。
Args:
dir_path: ディレクトリパス
Returns:
PNGファイルパスのリスト
"""
files = os.listdir(dir_path)
png_files = [f for f in files if f.endswith(".png")]
return png_files
##---
def get_color_counts(result_img):
#def get_color_percentages(result_img):
"""
画像の色ごとの割合を計算します。
Args:
result_img: 入力画像
Returns:
緑、赤、青の割合のリスト
"""
# 画像の形状を取得
height, width, channels = result_img.shape
# 各色の画素数をカウント
green_count = 0
red_count = 0
blue_count = 0
for i in range(height):
for j in range(width):
b, g, r = result_img[i, j]
if g == 192 and r == 0 and b == 0:
green_count += 1
elif r > g and r > b:
red_count += 1
elif b > g and b > r:
blue_count += 1
## 割合を計算
#total_count = height * width
#green_percentage = green_count / total_count
#red_percentage = red_count / total_count
#blue_percentage = blue_count / total_count
#
#return green_percentage, red_percentage, blue_percentage
return green_count, red_count, blue_count
file_pathes = ["A", "B", "result"]
image_files_A = get_png_files(file_pathes[0])
image_files_B = get_png_files(file_pathes[1])
page = 0
for image_file_A, image_file_B in zip(image_files_A, image_files_B):
page += 1
# 画像Aを読み込む
print(image_file_A)
print(image_file_B)
img_a = cv2.imread(file_pathes[0] + "\\" + image_file_A)
# 画像Bを読み込む
img_b = cv2.imread(file_pathes[1] + "\\" + image_file_B)
# 画像Aの黒画素を赤色に変更、条件に合わない箇所は白色に変更
mask_a = np.sum(img_a, axis=2) <= 200 * 3
img_a_colored = np.zeros_like(img_a)
img_a_colored[mask_a] = [0, 0, 255] # 赤色
img_a_colored[np.logical_not(mask_a)] = [255, 255, 255] # 白色
# 画像Bの黒画素を青色に変更、条件に合わない箇所は白色に変更
mask_b = np.sum(img_b, axis=2) <= 200 * 3
img_b_colored = np.zeros_like(img_b)
img_b_colored[mask_b] = [255, 0, 0] # 青色
img_b_colored[np.logical_not(mask_b)] = [255, 255, 255] # 白色
# 一致する画素を紫色に変更、その他の箇所は白色のまま
result = cv2.addWeighted(img_a_colored, 0.5, img_b_colored, 0.5, 0)
result[np.logical_and(mask_a, mask_b)] = [0, 192, 0] # 緑[0, 192, 0] 紫色[255, 0, 255]
# 画像の色数をカウントする
green, red, blue = get_color_counts(result)
#green, red, blue = get_color_count(result)
# テキストを描画する
total = green + red + blue
cv2.putText(result, f"{image_file_A} - {image_file_B} : G={green} / {total}({round(green/total*100, 2)}%)", (10, result.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0), 2)
# 結果画像を保存
print(file_pathes[2] + f'\\result_{page:02}.png')
cv2.imwrite(file_pathes[2] + f'\\result_{page:02}.png', result)
## 画像を表示する
#cv2.imshow('imageA', img_a_colored)
#cv2.imshow('imageB', img_b_colored)
#cv2.imshow('reslut', result)
#
## キー入力待ち
#cv2.waitKey(0)
#
## ウィンドウを閉じる
#cv2.destroyAllWindows()
0 件のコメント:
コメントを投稿