簡體   English   中英

Python OpenCV-將彩色蒙版應用於圖像

[英]Python OpenCV - apply colored mask to image

我得到以下東西:

  • 使用OpenCV讀取的圖像(numpy數組)
  • 與圖像大小相同的二進制蒙版
  • 顏色字符串,例如'red''blue'

:在將蒙版添加到圖像之前,我該如何着色? 明確地:給定顏色字符串,如何將顏色通道添加到二進制蒙版

我知道如何添加蒙版(例如,使用cv2.addWeighted(mask,alpha,image,1-alpha,0,image) ),但我不知道如何使用簡單的cv2.addWeighted(mask,alpha,image,1-alpha,0,image)將二進制蒙版轉換為顏色空間'作為輸入。 我知道這在rgb = PIL.ImageColor.getrgb(color) PIL中rgb = PIL.ImageColor.getrgb(color) ,但是我不知道如何使用OpenCV做到這一點!

編輯 :我設法獲得通道元組(0,0,0)中的顏色,目前我的解決方法是:

mask = cv2.cvtColor(mask, cv2.COLOR_GRAY2RGB)
mask[np.where((mask == [1,1,1]).all(axis = 2))] = color
cv2.addWeighted(mask,alpha,image,1-alpha,0,image)

但是問題是,現在圖像是帶有彩色地圖的灰度...所以第一行需要交換

您可以使用更簡單,更本地化的方法。 如果您在一個通道上應用了不均勻的移位,那么什么是彩色濾光片? 我通常只使用np.power 假設img是圖像的3D RGB矩陣:

img = np.power(img,[1.5, 1.0, 1.0]) # shift the reds
img = np.power(img,[1.0, 1.5, 1.0]) # shift the greens
img = np.power(img,[1.2, 1.2, 1.0]) # orange type? (I suck at color mixing, you'll find out the one you need to shift) (since all your colors are made from a combination of these three basic ones)

當我發現這個技巧時,我只是停止使用openCV和PIL(順便提一下,不推薦使用skimage

要將過濾器僅應用於蒙版部分,可以執行以下操作:

mask =  numpy.expand_dims(mask, 2) 
mask = numpy.repeat(mask, 3, axis=2) # give the mask the same shape as your image
colors = {"red": [0.1,0.,0.], "blue": [0.,0.,0.1]} # a dictionary for your colors, experiment with the values
colored_mask = numpy.multiply(mask, colors["red"])  # broadcast multiplication (thanks to the multiplication by 0, you'll end up with values different from 0 only on the relevant channels and the right regions)
img = img+colored_mask # element-wise sum (sinc img and mask have the same shape)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM