[英]how to separate image using color channel in python?
Hello I want to separate an object based it's color into a new image using python PIL您好,我想使用 python PIL 将基于其颜色的 object 分离为新图像
but I don't quite get the gasp of it.但我不太明白。 I'm still new with python.我还是 python 的新手。
what I already done is a code from matlab and it works我已经完成的是来自 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)
Can I get a proper explanation about how you do it using python PIL?我能否正确解释您如何使用 python PIL 进行操作?
thank you very much非常感谢您
edit:编辑:
What I'm trying to do is something like this我想做的是这样的
https://imgur.com/6n1QCfR https://imgur.com/6n1QCfR
Then the result is this然后结果是这样的
Here is a very easy way to do it using PIL/Pillow:这是使用 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')
Note #1: The image is stored in a 3 dimensional array, height x width x RGB channels.注意 #1:图像存储在 3 维数组中,高度 x 宽度 x RGB 通道。 Red is in channel 0, so it is na[:,:,0]
and na[...,0]
is shorthand for that same thing.红色在通道 0 中,所以它是na[:,:,0]
并且na[...,0]
是同一事物的简写。
Note #2: Green is in the second channel starting from index 0, so the green pixels can be addressed using na[:,:,1]
or equally na[...,1]
注意 #2:绿色在从索引 0 开始的第二个通道中,因此可以使用na[:,:,1]
或同样使用na[...,1]
来寻址绿色像素
Note that JPEG is lossy and often a poor choice for intermediate files in image processing because it changes values to make files smaller.请注意,JPEG 是有损的,并且对于图像处理中的中间文件通常是一个糟糕的选择,因为它会更改值以使文件更小。 Consider using PNG which is lossless.考虑使用无损的 PNG。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.