2017-10-12 277 views
0

我擁有stanrd 52遊戲卡的圖像。其中一些是黑色的,一些是紅色的。已經訓練了一個神經網絡來正確識別它們。現在事實證明,有時使用綠色而不是紅色。這就是爲什麼我要將所有綠色(ish)圖像轉換爲紅色(ish)的原因。如果它們變黑或變紅,則應儘可能不要變化太大或根本不變。將綠色轉換爲紅色

什麼是實現這一目標的最佳方式是什麼?

enter image description here

+0

同樣,你需要定義什麼是綠的,什麼是瑞迪施,數學。 – Divakar

+0

我會使用opencv庫,在圖像中讀取爲RGB(有三個紅色,綠色藍色通道),然後嘗試切換R和G通道,看看是否能得到你想要的。 – flyingmeatball

+0

我沒有任何其他的定義,除了一切都是綠色的,比黑色或紅色或白色更綠。只有那四種顏色是重要的。綠色,紅色,白色和黑色。 – Nickpick

回答

1

下面是使用一種方法的公差值對-ish因素決定設置一個數學符號,以它 -

def set_image(a, tol=100): #tol - tolerance to decides on the "-ish" factor 

    # define colors to be worked upon 
    colors = np.array([[255,0,0],[0,255,0],[0,0,0],[255,255,255]]) 

    # Mask of all elements that are closest to one of the colors 
    mask0 = np.isclose(a, colors[:,None,None,:], atol=tol).all(-1) 

    # Select the valid elements for edit. Sets all nearish colors to exact ones 
    out = np.where(mask0.any(0)[...,None], colors[mask0.argmax(0)], a) 

    # Finally set all green to red 
    out[(out == colors[1]).all(-1)] = colors[0] 
    return out.astype(np.uint8) 

一個內存更有效的方法是依次通過選擇性的那些顏色,像這樣 -

def set_image_v2(a, tol=100): #tol - tolerance to decides on the "-ish" factor 

    # define colors to be worked upon 
    colors = np.array([[255,0,0],[0,255,0],[0,0,0],[255,255,255]]) 

    out = a.copy() 
    for c in colors: 
     out[np.isclose(out, c, atol=tol).all(-1)] = c 

    # Finally set all green to red 
    out[(out == colors[1]).all(-1)] = colors[0] 
    return out 

採樣運行 -

輸入圖像:

enter image description here

from PIL import Image 
img = Image.open('green.png').convert('RGB') 
x = np.array(img) 
y = set_image(x) 
z = Image.fromarray(y, 'RGB') 
z.save("tmp.png") 

輸出 -

enter image description here

+0

我試過用 img = Image.open( 'c:/temp/green.png') x = np.array(img) y = set_image(x) z = Image.fromarray(y,'RGB') 但結果是完全是綠色的轉彎黑色與對角綠色條紋。事實上,這個問題上面的圖像幾乎全黑。 – Nickpick

+0

@nickpick檢查編輯。我們需要在那裏進行類型轉換。 – Divakar

+0

仍然會出現黑色圖像,儘管我使用了您的示例和圖像 – Nickpick

相關問題