具有多个条件的Python numpy数组可遍历图像 [英] Python numpy array with multiple conditions to iterate over image

查看:164
本文介绍了具有多个条件的Python numpy数组可遍历图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在过滤一些图像以去除不必要的背景,到目前为止,在检查像素BGR(使用openCV)值方面取得了最大的成功.问题在于,使用2个嵌套循环遍历图像太慢了:

I'm filtering some images to remove unnecessary background, and so far have had best success with checking for pixel BGR (using openCV) values. The problem is that iterating over the image with 2 nested loops is way too slow:

h, w, channels = img.shape
    for x in xrange(0,h):
        for y in xrange (0,w):
            pixel = img[x,y]
            blue = pixel[0]
            green = pixel[1]
            red = pixel[2]

            if green > 110:
                img[x,y] = [0,0,0]
                continue

            if blue < 100 and red < 50 and green > 80:
                img[x,y] = [0,0,0]
                continue

还有更多类似的if语句,但是您知道了.问题是在i7上的672x1250上,这大约需要10秒钟.

There are a couple of more similar if-statements, but you get the idea. The problem is this takes around 10 seconds on a 672x1250 on an i7.

现在,我可以像这样轻松地执行第一个if语句:

Now, I can easily do the first if statement like so:

img[np.where((img > [0,110,0]).all(axis=2))] = [0,0,0]

它的速度要快得多,但是我似乎无法使用np.where在其他if语句中使用多个条件.

And it's much much faster, but I can't seem to do the other if-statements with multiple conditions in them using np.where.

这是我尝试过的:

img[np.where((img < [100,0,0]).all(axis=2)) & ((img < [0,0,50]).all(axis=2)) & ((img > [0,80,0]).all(axis=2))] = [0,0,0]

但是会引发错误:

ValueError: operands could not be broadcast together with shapes (2,0) (1250,672)

任何想法如何使用np.where(或任何比2个嵌套循环都快的东西)正确地迭代图像会很有帮助!

Any ideas how to properly iterate over the image using np.where (or anything that's faster than 2 nested loop) will help a lot!

推荐答案

您可以这样表达条件(没有np.where):

You could express the conditions (without np.where) like this:

import numpy as np
img = np.random.randint(255, size=(4,4,3))
blue, green, red = img[..., 0], img[..., 1], img[..., 2]
img[(green > 110) | ((blue < 100) & (red < 50) & (green > 80))] = [0,0,0]


In [229]: %%timeit img = np.random.randint(255, size=(672,1250,3))
   .....: blue, green, red = img[..., 0], img[..., 1], img[..., 2]
   .....: img[(green > 110) | ((blue < 100) & (red < 50) & (green > 80))] = [0,0,0]
   .....: 
100 loops, best of 3: 14.9 ms per loop

In [240]: %%timeit img = np.random.randint(255, size=(672,1250,3))
   .....: using_loop(img)
   .....: 
1 loop, best of 3: 1.39 s per loop

其中using_loop(img)执行问题中发布的双循环.

where using_loop(img) executes the double loop posted in the question.

这篇关于具有多个条件的Python numpy数组可遍历图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆