array遍历所有像素来查找图像中的所有绿色像素

array遍历所有像素来查找图像中的所有绿色像素

本文介绍了Python 3:我试图通过使用np.array遍历所有像素来查找图像中的所有绿色像素,但无法绕开索引错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码当前包括加载图像,这是成功的,并且我认为与该问题没有任何联系.

My code currently consists of loading the image, which is successful and I don't believe has any connection to the problem.

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

Then I go on to transform the color image into a np.array named rgb

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

仔细检查一下我对这个数组的理解,以防可能是问题的根源,它是一个数组,其rgb [x坐标,y坐标,色带]的值在0-255之间红色,绿色或蓝色.

To double check my understanding of this array, in case that may be the root of the issue, it is an array such that rgb[x-coordinate, y-coordinate, color band] which holds the value between 0-255 of either red, green or blue.

然后,我的想法是制作一个嵌套的for循环遍历图像的所有像素(620px,400px),并根据绿色与蓝色和红色的比率对它们进行排序,以尝试找出较绿色的像素并进行设置所有其他都设为黑色或0.

Then, my idea was to make a nested for loop to traverse all pixels of my image (620px,400px) and sort them based on the ratio of green to blue and red in an attempt to single out the greener pixels and set all others to black or 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]

尝试执行此操作时收到的错误如下:

The error I am receiving when trying to run this is as follows:

IndexError:索引400超出了尺寸为400的轴0的边界

IndexError: index 400 is out of bounds for axis 0 with size 400

我认为这可能与给定i和j的范围有关,因此我尝试仅对图像的一小部分进行排序,但仍然遇到相同的错误.在这一点上,我什至不知道错误的根源是什么,更不用说解决方案了.

I thought it may have something to do with the bounds I was giving i and j so I tried only sorting through a small inner portion of the image but still got the same error. At this point I am lost as to what is even the root of the error let alone even the solution.

推荐答案

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

In direct answer to your question, the y axis is given first in numpy arrays, followed by the x axis, so interchange your indices.

直接减少,您会发现for循环在Python中非常慢,通常最好使用numpy向量化操作.另外,您通常会发现在 HSV色彩空间中更容易找到绿色阴影.

Less directly, you will find that for loops are very slow in Python and you are generally better off using numpy vectorised operations instead. Also, you will often find it easier to find shades of green in HSV colourspace.

让我们从HSL色轮开始吧:

Let's start with an HSL colour wheel:

,并假设您要将所有绿色变为黑色.因此,在该Wikipedia页面上,与Green对应的色相为120度,这意味着您可以执行以下操作:

and assume you want to make all the greens into black. So, from that Wikipedia page, the Hue corresponding to Green is 120 degrees, which means you could do this:

#!/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/透明度,并匹配了红色像素,从而带来了更多乐趣:

Here is a slightly improved version that retains the alpha/transparency, and matches red pixels for extra fun:

#!/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,颜色范围,颜色范围,范围,质数.

Keywords: Image processing, PIL, Pillow, Hue Saturation Value, HSV, HSL, color ranges, colour ranges, range, prime.

这篇关于Python 3:我试图通过使用np.array遍历所有像素来查找图像中的所有绿色像素,但无法绕开索引错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 04:36