from PIL import Image
# 读取图像文件
image_path = r'D:\yi\youxiwaigua\cache\16955642530.png' # r'C:\Users\王小丫\Desktop\img\寄快递.png'#r'D:\yi\youxiwaigua\cache\16955642530.png'
image = Image.open(image_path)
# 指定要检查的颜色范围
target_color = (255, 255, 0) # 指定为红色,格式为RGB
tolerance = 50 # 允许的颜色容差范围
# 遍历图像的每个像素
width, height = image.size
for x in range(width):
for y in range(height):
pixel_color = image.getpixel((x, y))
if all(abs(pixel_color[i] - target_color[i]) <= tolerance for i in range(3)):
print("指定范围内的颜色存在于图像中")
break
else:
continue
break
else:
print("指定范围内的颜色不存在于图像中")
封装后
def detect_rgb_in(image_path: str, target_color: tuple, tolerance_range: int):
'''
检测指定像素是否在图片内
@params image_path --> 图片路径;
@params target_color --> 指定颜色rgb
@params tolerance_range --> 色差范围;
Eg:
detect_rgb_in(r'D:\yi\youxiwaigua\cache\16955642530.png', (255, 255, 0), 50)
'''
# 读取图像文件
# image_path = r'D:\yi\youxiwaigua\cache\16955642530.png' # r'C:\Users\王小丫\Desktop\img\寄快递.png'#r'D:\yi\youxiwaigua\cache\16955642530.png'
image = Image.open(image_path)
# 指定要检查的颜色范围
target_color = target_color # (255, 255, 0) # 指定为红色,格式为RGB
tolerance = tolerance_range# 50 # 允许的颜色容差范围
_true = False
# 遍历图像的每个像素
width, height = image.size
for x in range(width):
for y in range(height):
pixel_color = image.getpixel((x, y))
if all(abs(pixel_color[i] - target_color[i]) <= tolerance for i in range(3)):
#print("指定范围内的颜色存在于图像中")
_true = True
break
else:
continue
break
return _true