Python+OpenCV繪制多instance的Mask圖像
更新時(shí)間:2022年06月08日 14:03:23 作者:SpikeKing
Mask圖像中,不同值表示不同的實(shí)例(instance)。本文將詳細(xì)為大家講講如何利用OpenCV繪制多instance的Mask圖像,感興趣的可以學(xué)習(xí)一下
目標(biāo):Mask中,不同值表示不同的實(shí)例(instance),在原圖中,繪制不同的instance實(shí)例,每個(gè)實(shí)例用不同顏色表示,實(shí)例邊界用白色表示。
源碼:
def generate_colors(n_colors, seed=47):
"""
隨機(jī)生成顏色
"""
np.random.seed(seed)
color_list = []
for i in range(n_colors):
color = (np.random.random((1, 3)) * 0.8).tolist()[0]
color = [int(j * 255) for j in color]
color_list.append(color)
return color_list
def draw_mask_layers(image, mask_layers, mask_tk=1):
"""
繪制多層的mask,包含mask的邊界,mask中不同值表示不同的instance
:param image: 3通道圖像
:param mask_layers: 多instance的mask
:param mask_tk: 邊界的厚度
:return: 繪制邊界框
"""
img_copy = copy.copy(image)
# 拆分Mask
h, w = mask_layers.shape[:2]
mask_id = np.unique(mask_layers)[1:] # 獲取Mask的ID, 0是背景
masks = []
for i in mask_id:
m = np.zeros((h, w), dtype=bool)
m[mask_layers == i] = True
masks.append(m)
# 繪制顏色區(qū)域
color_list = generate_colors(len(masks))
for idx, mask in enumerate(masks):
img_copy[mask] = color_list[idx] # 繪制顏色框
image = cv2.addWeighted(image, 0.5, img_copy, 0.5, 0) # 合并mask
# 繪制邊界,邊界不需要透視效果
for idx, mask in enumerate(masks):
cnt_mask = np.zeros((h, w))
cnt_mask[mask] = 255
cnt_mask = cnt_mask.astype(np.uint8)
contours, _ = cv2.findContours(cnt_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(image, contours, -1, (255, 255, 255), mask_tk) # 繪制白色邊界
return image
原圖:

Mask圖像:

以上就是Python+OpenCV繪制多instance的Mask圖像的詳細(xì)內(nèi)容,更多關(guān)于Python OpenCV Mask圖像的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python的列表List求均值和中位數(shù)實(shí)例
這篇文章主要介紹了python的列表List求均值和中位數(shù)實(shí)例,具有很好對參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
python機(jī)器學(xué)習(xí)算法與數(shù)據(jù)降維分析詳解
這篇文章主要為大家介紹了python機(jī)器學(xué)習(xí)算法與數(shù)據(jù)降維的分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2021-11-11
python實(shí)現(xiàn)LRU熱點(diǎn)緩存及原理
LRU算法根據(jù)數(shù)據(jù)的歷史訪問記錄來進(jìn)行淘汰數(shù)據(jù),其核心思想是“如果數(shù)據(jù)最近被訪問過,那么將來被訪問的幾率也更高”。 。這篇文章主要介紹了python實(shí)現(xiàn)LRU熱點(diǎn)緩存,需要的朋友可以參考下2019-10-10

