import numpy as np
import cv2
def segment_image_by_color(image_path, min_thresh, max_thresh):
# 读取图片
image = cv2.imread(image_path)
# 转换到HSV色彩空间
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
# 设定HSV色彩空间中的蓝色范围
lower_blue = np.array([min_thresh[0], min_thresh[1], min_thresh[2]])
upper_blue = np.array([max_thresh[0], max_thresh[1], max_thresh[2]])
# 根据颜色范围创建掩模,注意这里是HSV图像
mask = cv2.inRange(hsv_image, lower_blue, upper_blue)
# 对原图像和掩模进行位运算,实现分割
segmented_image = cv2.bitwise_and(image, image, mask=mask)
return segmented_image
# 示例使用
image_path = 'path_to_your_image.jpg'
min_thresh = [100, 150, 0] # HSV中蓝色的最小阈值
max_thresh = [140, 255, 255] # HSV中蓝色的最大阈值
segmented_image = segment_image_by_color(image_path, min_thresh, max_thresh)
cv2.imshow('Segmented Image', segmented_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
这段代码首先定义了一个函数segment_image_by_color
,它接受图像路径、最小阈值和最大阈值作为输入,然后读取图像,将其从BGR色彩空间转换到HSV色彩空间,创建蓝色的阈值掩模,应用掩模进行图像分割,并显示结果。这个函数可以通过更改阈值来适应不同颜色的分割任务。