我的代码目前包括加载映像,这是成功的,我不认为与问题有任何联系。
然后,我继续将彩色图像转换为一个名为rgb的np.array。
# convert image into array
rgb = np.array(img)
red = rgb[:,:,0]
green = rgb[:,:,1]
blue = rgb[:,:,2]
为了再次检查我对这个数组的理解,万一这可能是问题的根源,它是一个数组,它的rgbx-坐标,y-坐标,颜色带,它的值在0-255之间,无论是红色,绿色还是蓝色。
然后,我的想法是做一个嵌套的for循环,遍历图像的所有像素(620 in,400 in),并根据绿色与蓝色和红色的比例对它们进行排序,试图选择更绿色的像素,并将所有其他像素设置为黑色或0。
for i in range(xsize):
for j in range(ysize):
color = rgb[i,j] <-- Index error occurs here
if(color[0] > 128):
if(color[1] < 128):
if(color[2] > 128):
rgb[i,j] = [0,0,0]
我在尝试运行时所收到的错误如下所示:
IndexError:对于尺寸为400的0轴,索引400超出了界限
我认为这可能与我给i和j的界有关,所以我只试着对图像的一小部分内部进行排序,但仍然得到了相同的错误。在这一点上,我不知道什么甚至是错误的根源,更不用说解决方案了。
发布于 2018-09-05 03:09:00
为了直接回答您的问题,首先在y
数组中给出numpy
轴,然后给出x
轴,因此交换索引。
更直接地说,您会发现for
循环在Python中非常慢,您通常最好使用numpy
矢量化操作。另外,您还会发现在HSV色彩空间中更容易找到绿色的阴影。
让我们从HSL色轮开始:
假设你想把所有的绿色变成黑色。因此,在维基百科页面中,绿色对应的颜色是120度,这意味着你可以这样做:
#!/usr/local/bin/python3
import numpy as np
from PIL import Image
# Open image and make RGB and HSV versions
RGBim = Image.open("image.png").convert('RGB')
HSVim = RGBim.convert('HSV')
# Make numpy versions
RGBna = np.array(RGBim)
HSVna = np.array(HSVim)
# Extract Hue
H = HSVna[:,:,0]
# Find all green pixels, i.e. where 100 < Hue < 140
lo,hi = 100,140
# Rescale to 0-255, rather than 0-360 because we are using uint8
lo = int((lo * 255) / 360)
hi = int((hi * 255) / 360)
green = np.where((H>lo) & (H<hi))
# Make all green pixels black in original image
RGBna[green] = [0,0,0]
count = green[0].size
print("Pixels matched: {}".format(count))
Image.fromarray(RGBna).save('result.png')
这意味着:
下面是一个稍微改进的版本,它保留alpha/透明性,并匹配红色像素以获得额外的乐趣:
#!/usr/local/bin/python3
import numpy as np
from PIL import Image
# Open image and make RGB and HSV versions
im = Image.open("image.png")
# Save Alpha if present, then remove
if 'A' in im.getbands():
savedAlpha = im.getchannel('A')
im = im.convert('RGB')
# Make HSV version
HSVim = im.convert('HSV')
# Make numpy versions
RGBna = np.array(im)
HSVna = np.array(HSVim)
# Extract Hue
H = HSVna[:,:,0]
# Find all red pixels, i.e. where 340 < Hue < 20
lo,hi = 340,20
# Rescale to 0-255, rather than 0-360 because we are using uint8
lo = int((lo * 255) / 360)
hi = int((hi * 255) / 360)
red = np.where((H>lo) | (H<hi))
# Make all red pixels black in original image
RGBna[red] = [0,0,0]
count = red[0].size
print("Pixels matched: {}".format(count))
result=Image.fromarray(RGBna)
# Replace Alpha if originally present
if savedAlpha is not None:
result.putalpha(savedAlpha)
result.save('result.png')
关键词:图像处理,PIL,枕头,色度饱和值,HSV,HSL,颜色范围,颜色范围,范围,质数。
https://stackoverflow.com/questions/52179821
复制