将一张图中亮度超过128的区域变成红色输出
def reshape_gray_to_color( img):"""一个img的shape等于img.shape (319, 460) ,将该img的shape变成img.shape (319, 460, 3)"""# 创建新的形状(在最后面加入一个“3”以表示三个颜色通道)new_shape = img.shape + (3,)# 按照新形状创建一个空白数组img_reshaped = np.zeros(new_shape, dtype=img.dtype)# 将原始图像复制到新数组中对应的位置img_reshaped[:, :, 0] = imgimg_reshaped[:, :, 1] = imgimg_reshaped[:, :, 2] = imgreturn img_reshapeddef highlight_bright_pixels(img, brightness_threshold=128):"""将输入图像中亮度大于等于给定值的像素点标记为红色。:param img: 输入图像:param brightness_threshold: 亮度值阈值,默认为 128。:return: 处理后的图像和标记像素数。"""#img = self.reshape_gray_to_color(img) ## 将 RGB 图像转换为 HSV 图像hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)# 提取亮度通道value_channel = hsv_img[:, :, 2]# 比较亮度值与阈值,返回 True/False 数组bright_pixels_mask = value_channel >= brightness_threshold# 在掩模下将亮度值大于阈值的区域设置成红色output_img = img.copy()output_img[bright_pixels_mask] = (0, 0, 255) # 红色# 统计红色像素的数量num_red_pixels = np.count_nonzero(bright_pixels_mask)return output_img, num_red_pixels
#读取一张图片并显示
img = cv2.imread("keng/9_head_filter_old_mask.jpg")
cv2.imshow("image",img)
print("img.shape",img.shape)
img2,a = highlight_bright_pixels(img)
cv2.imshow("image2",img2)
print(a)
cv2.waitKey(0)