如何实现判断像素HSV值是否在指定区间的Python函数?
修正HSV像素区间判断函数
需求与问题
需要实现一个函数,当输入的HSV像素值落在指定区间时返回1,否则返回0。用户尝试的代码如下:
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 """
期望的使用方式及输出:
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
修正后的代码
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 返回一个函数,用于判断输入的HSV像素值是否在指定区间内 """ def check_pixel(pixel): h, s, v = pixel # 逐个通道判断是否在区间内,全部满足则返回1,否则返回0 if hlow <= h <= hhigh and slow <= s <= shigh and vlow <= v <= vhigh: return 1 else: return 0 return check_pixel
关键修正点
- 闭包结构:外层函数接收区间参数后,返回内层函数
check_pixel,实现示例中先定义is_black再传入像素值的调用逻辑。 - 正确区间判断:替换原代码中错误的
min >= high逻辑,改为逐个验证H、S、V通道是否落在对应上下限之间。 - 参数解构:将输入的像素元组拆分为h、s、v分量,便于分别校验。
测试验证
运行示例代码:
is_black = pixel_constraint(0, 255, 0, 255, 0, 10) print(is_black((231, 82, 4))) # 输出1 print(is_black((231, 72, 199))) # 输出0
结果符合预期。
内容的提问来源于stack exchange,提问作者Erik
相关产品推荐
相关产品推荐

