img:
label:
合併達到的效果:
實現程式碼:
點選檢視程式碼
import cv2
import numpy as np
from PIL import Image
def add_legend(image, colors, labels, alpha=1):
"""
在影像的右上角新增圖例,使用固定的尺寸。
:param image: 輸入的BGR影像。
:param colors: 顏色字典,鍵是類值,值是顏色元組(B, G, R)。
:param labels: 標籤字典,鍵是類值,值是標籤文字。
:param alpha: 疊加透明度。
:return: 帶圖例的影像。
"""
# 影像尺寸
height, width = image.shape[:2]
# 固定圖例尺寸和引數
legend_height = 20
legend_width = 150
legend_padding = 10
color_box_size = 15
text_offset = 20
text_font_scale = 0.5
text_thickness = 1
line_height = 20 # 每一行的高度
# 建立圖例的背景
legend = np.zeros((legend_height * len(labels) + legend_padding * 2, legend_width, 3), dtype=np.uint8)
for idx, (key, color) in enumerate(colors.items()):
# 設定圖例的顏色框
top_left = (legend_padding, idx * line_height + legend_padding)
bottom_right = (legend_padding + color_box_size, idx * line_height + legend_padding + color_box_size)
cv2.rectangle(legend, top_left, bottom_right, color[::1], -1) # 顏色需要從 BGR 轉換為 RGB
# 新增標籤文字
text_position = (legend_padding + color_box_size + text_offset, top_left[1] + color_box_size)
cv2.putText(legend, labels[key], text_position, cv2.FONT_HERSHEY_SIMPLEX, text_font_scale, (255, 255, 255),
text_thickness)
# 計算圖例位置
legend_x = width - legend_width - legend_padding
legend_y = legend_padding
# 將圖例疊加到原影像右上角
overlay = image.copy()
overlay[legend_y:legend_y + legend.shape[0], legend_x:legend_x + legend.shape[1]] = legend
# 透明混合
result = cv2.addWeighted(overlay, alpha, image, 1 - alpha, 0)
return result
def save_img_label(image_path,mask_path,save_path):
# image_path=r'.\data_insar\path_all\data\0.png'#三通道彩色圖
# mask_path=r'.\data_insar\path_all\annotations\0.png' #對應的單通道灰度圖示籤掩碼
#讀取原圖
image=cv2.imread(image_path)
mask=Image.open(mask_path)
mask = np.array(mask)
# 建立一個空白的彩色疊加圖 (與原圖相同大小,但包含透明度通道)
overlay = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.uint8)
colors = {
1: (0, 0, 255), # 類1 - 紅色
}
colors_lengend = {
1: (0, 0, 255), # 類1 - 紅色
}
labels = {
1: 'cat',
}
# 遍歷掩碼中的每個類別,為每個類別設定顏色
for value, color in colors.items():
overlay[mask == value] = color
combined = cv2.addWeighted(overlay, 0.3, image, 1, 0)
# 新增圖例到右上角
result_with_legend = add_legend(combined, colors_lengend, labels, alpha=0.5)
#儲存結果
cv2.imwrite(os.path.join(save_path,'cat_label.png'), result_with_legend)
in_img_path = r".\data\cat.png"
in_json_path = r".\annotations\cat_json\label.png"
save_path = r".\test"
save_img_label(in_img_path,in_json_path,save_path)
其中很大部分都是參考https://www.cnblogs.com/wancy/p/18212547,詳細請參考該博主