Home > OS >  Check if number is between a range
Check if number is between a range

Time:10-02

I'm trying to write a function that returns 1 if value is between input and 0 if not. Here's what I tried

def pixel_constraint(hlow, hhigh, slow, shigh, vlow, vhigh):
    """
    H - Hue:       (0-255) e.g red/cyan
    S - Saturation (0-255) e.g bright/not
    V - Value      (0-255) e.g black/white
    
    min = (hlow, slow, vlow)
    high = (hhigh, shigh, vhigh)
    if min >= high:
          return 1
      else:
          return 0
    """

Desired output:

    is_black = pixel_constraint(0, 255, 0, 255, 0, 10) 
    # Between (0 -> 255, 0 -> 255, 0 -> 10)

    is_black((231, 82, 4))
    >>> 1
    is_black((231, 72, 199))
    >>> 0

CodePudding user response:

Assuming that your real intent is to have pixel_constraint return a function, this matches your desired output:

def pixel_constraint(hlow, hhigh, slow, shigh, vlow, vhigh):
    def f(pixel):
        h,s,v = pixel
        return int(hlow <= h <= hhigh and slow <= s <= shigh and vlow <= v <= vhigh)
    return f

is_black = pixel_constraint(0, 255, 0, 255, 0, 10) 
# Between (0 -> 255, 0 -> 255, 0 -> 10)

print(is_black((231, 82, 4))) #1
print(is_black((231, 72, 199))) #0
  • Related