![](/img/trans.png)
[英]how to convert alpha channel of the image to white color using opencv python?
[英]how to separate image using color channel in python?
您好,我想使用 python PIL 將基於其顏色的 object 分離為新圖像
但我不太明白。 我還是 python 的新手。
我已經完成的是來自 matlab 的代碼,它可以工作
G = imread('x.png');
L = G;
for i=1:217 #this is image height
for j=1:286 #this is image width
for k=1:3 #this is color RGB channel
if(L(i,j,2) < 174) #if green value is under 174
L(i,j,k) = L(i,j,k);
else
L(i,j,k) = 256; #change to white
end
if(L(i,j,3) < 174) #if blue value is under 174
L(i,j,k) = L(i,j,k);
else
L(i,j,k) = 256; #change to white
end
end
end
end
imshow(L)
我能否正確解釋您如何使用 python PIL 進行操作?
非常感謝您
編輯:
我想做的是這樣的
然后結果是這樣的
這是使用 PIL/Pillow 的一種非常簡單的方法:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
# Load image and ensure it is RGB (not palette)
im = Image.open('circles.jpg').convert('RGB')
# Make into Numpy array so we can do fast, vectorised operations
na = np.array(im)
# Make a mask, which is True wherever Blue channel is high, False elsewhere - see #1 below
mBlueHi = na[...,2] >= 174
# Likewise for Green channel - see #2 below
mGreenHi = na[...,1] >= 174
# In our original image "na", anywhere the Green or Blue mask is set, make it white
na[mGreenHi | mBlueHi] = [255,255,255]
# Make back into PIL Image and save
Image.fromarray(na).save('result.png')
注意 #1:圖像存儲在 3 維數組中,高度 x 寬度 x RGB 通道。 紅色在通道 0 中,所以它是na[:,:,0]
並且na[...,0]
是同一事物的簡寫。
注意 #2:綠色在從索引 0 開始的第二個通道中,因此可以使用na[:,:,1]
或同樣使用na[...,1]
來尋址綠色像素
請注意,JPEG 是有損的,並且對於圖像處理中的中間文件通常是一個糟糕的選擇,因為它會更改值以使文件更小。 考慮使用無損的 PNG。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.