Python 3:我试图通过使用 np.array 遍历所有像素来查找图像中的所有绿色像素,但无法绕过索引错误

Whi*_*oes 3 python arrays rgb image

我的代码目前包括加载图像,这是成功的,我认为与问题没有任何联系。

然后我继续将彩色图像转换为名为 rgb 的 np.array

    # convert image into array
    rgb = np.array(img)
    red = rgb[:,:,0]
    green = rgb[:,:,1]
    blue = rgb[:,:,2]
Run Code Online (Sandbox Code Playgroud)

为了仔细检查我对这个数组的理解,以防这可能是问题的根源,它是一个数组,使得 rgb[x-coordinate, y-coordinate, color band] 保持 0-255 之间的值、绿色或蓝色。

然后,我的想法是制作一个嵌套的 for 循环来遍历我图像的所有像素(620px,400px)并根据绿色与蓝色和红色的比例对它们进行排序,以尝试挑出更绿色的像素并将所有其他像素设置为黑色或 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]
Run Code Online (Sandbox Code Playgroud)

我在尝试运行时收到的错误如下:

索引错误:索引 400 超出轴 0 的范围,大小为 400

我认为这可能与我给 i 和 j 的边界有关,所以我尝试只对图像的一小部分内部进行排序,但仍然出现相同的错误。在这一点上,我什至不知道错误的根源是什么,更不用说解决方案了。

Mar*_*ell 10

在直接回答您的问题时,y轴首先在numpy数组中给出,然后是x轴,因此请交换索引。


不那么直接,您会发现forPython中的循环非常慢,通常最好使用向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')
Run Code Online (Sandbox Code Playgroud)

这使:

在此处输入图片说明


这是一个稍微改进的版本,保留了 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')
Run Code Online (Sandbox Code Playgroud)

关键词:图像处理,PIL,枕头,色相饱和度值,HSV,HSL,颜色范围,颜色范围,范围,素数。

在此处输入图片说明