Processing an image to extract green-screen mask I am using OpenCV to process an image, and in my code, I have to check / edit each pixel separately:

import cv2, numpy

# we just use an empty image for the purpose of this MCVE
img = cv2.imread("source.jpg")   
width = len(img[0])
height = len(img)

empty_img = numpy.zeros((height, width, 3), numpy.uint8)

i = 0
r = 0
c = 0

for line in img:
    c = 0

    for pixel in line:
        blue = pixel[0]
        green = pixel[1]
        red = pixel[2]

        if green != max(red, green, blue) or green &lt; 35:
            # this has a greenishy hue
            empty_img.itemset((r, c, 0), 255)

        c += 1
    r += 1


This code works, but is quite slow (it takes about 23 seconds to process the image). How could/should I speed this up?

source.jpg:


result should be:
Use conditional indexing:

RED, GREEN, BLUE = (2, 1, 0) # Your numbers

empty_img = numpy.zeros((height, width, 3), numpy.uint8)

reds = img[:, :, RED]
greens = img[:, :, GREEN]
blues = img[:, :, BLUE]

empty_img[(greens &lt; 35) | (reds &lt;= greens &gt;= blues)][BLUE] = 255


Edit:

empty_img[(greens &lt; 35) | ((reds &lt;= greens) &amp; (blues &lt;= greens))][BLUE] = 255


I was wondering if the compound relation would work. Sadly, not. This should. If it doesn't you can try composing it step by step - look at just the greens &lt; 35 case, then the reds &lt;=greens, etc.