You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将图像RGB/HSV值按相近范围合并、去噪并生成一维直方图?

图像颜色区间合并与一维直方图实现方案

现有一张RGB/HSV值范围为0~255的黑色渐变图像,需求如下:

  • 将像素按080、80160、160~255三个区间合并,同时去除噪声,得到目标效果图像
  • 生成原图的一维直方图(非三维直方图)

实现代码

以下是整合了颜色区间合并、去噪以及直方图生成的Python代码:

import numpy as np
import cv2 
import matplotlib.pyplot as plt

def process_img_and_hist(path):
    # 读取原图
    img = cv2.imread(path)
    if img is None:
        print("无法读取图像,请检查路径!")
        return
    
    # ---------------------- 1. 生成原图一维直方图(以V通道为例,更贴合黑色渐变特征) ----------------------
    hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    v_channel = hsv_img[:, :, 2]
    # 计算V通道一维直方图
    hist_v = cv2.calcHist([v_channel], [0], None, [256], [0, 256])
    
    # 绘制原图一维直方图
    plt.figure(figsize=(8, 4))
    plt.plot(hist_v, color='gray', label="原图V通道一维直方图")
    plt.xlabel("像素值")
    plt.ylabel("像素数量")
    plt.legend()
    plt.show()
    
    # ---------------------- 2. 颜色区间合并与去噪 ----------------------
    # 定义区间映射规则:将每个通道的像素值映射到对应区间的中点
    def map_interval(pixel):
        if pixel < 80:
            return 40
        elif pixel < 160:
            return 120
        else:
            return 200
    
    # 向量化映射函数,提升处理速度
    map_vec = np.vectorize(map_interval)
    # 对RGB三个通道分别进行区间映射
    merged_img = np.dstack((map_vec(img[:, :, 0]), map_vec(img[:, :, 1]), map_vec(img[:, :, 2])))
    merged_img = merged_img.astype(np.uint8)  # 转换为图像格式的uint8类型
    
    # 高斯滤波去除噪声
    denoised_img = cv2.GaussianBlur(merged_img, (3, 3), 0)
    
    # 显示处理后的图像
    cv2.imshow("处理后图像", denoised_img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    return denoised_img, hist_v

# 替换为你的图像路径
img_path = "/home/student_DC/desktop/optimization_11_10/output_11_10__002/22.png"
processed_img, original_hist = process_img_and_hist(img_path)

代码说明

  1. 一维直方图生成:针对黑色渐变图像,选择HSV空间的V(亮度)通道生成一维直方图,更能直观体现图像的亮度分布特征;也可根据需求替换为RGB的任意通道。
  2. 颜色区间合并:通过自定义映射函数,将每个像素值映射到对应区间的中点(080→40,80160→120,160255→200),实现相近颜色的合并;若需要更硬的边界效果,也可将中点替换为区间的上下限(如080→0,80~160→80等)。
  3. 去噪处理:使用高斯滤波cv2.GaussianBlur去除区间合并后可能出现的噪声,参数可根据图像实际噪声情况调整。

内容的提问来源于stack exchange,提问作者user20396381

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 19:50:24