You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何基于现有白色滤镜实现OpenCV C++黑色颜色滤镜?

Black Color Filter Implementation for OpenCV (C++)

Great question! Let's build this black filter to match the logic of your existing white filter—since HSV color space makes this really straightforward once you know the range for black.

Quick Recap of Your White Filter Logic

Your white filter targets pixels with high brightness (V channel) and low saturation (S channel) in HSV, which makes perfect sense for pure white and near-whites. For black, we'll flip this logic a bit.

HSV Range for Black

Black in HSV is defined by low brightness (V channel)—hue (H) and saturation (S) don't strictly matter for pure black, since even dark saturated colors (like deep red) can be considered "black" depending on your use case. Here's the breakdown:

  • Hue (H): 0 to 255 (all hues are allowed)
  • Saturation (S): 0 to 255 (all saturation levels are allowed, from pure gray to dark colored tones)
  • Value (V): 0 to your threshold (only dark pixels qualify)

The Black Filter Code

Here's the implementation that mirrors your white filter's structure:

static Mat blackcolorfilter(cv::Mat img, int threshold) {
    cv::Mat temp;
    // Convert input image to HSV space
    // Note: If your input is BGR (default for OpenCV imread()), use cv::COLOR_BGR2HSV instead!
    cv::cvtColor(img, temp, cv::COLOR_RGB2HSV);
    
    // Define HSV ranges for black
    cv::Scalar lowerBlack(0, 0, 0);
    cv::Scalar upperBlack(255, 255, threshold);
    
    // Apply the range mask (result is stored back in input img)
    cv::inRange(temp, lowerBlack, upperBlack, img);
    
    return img;
}

Key Details to Note

  • Threshold Control: The threshold parameter sets the maximum brightness a pixel can have to be classified as black. A value of 30 will only pick very dark/near-pure black pixels, while 80 will include darker grays and muted dark colors.
  • Color Space Check: Your original code uses CV_RGB2HSV—keep in mind OpenCV loads images as BGR by default. If you're using cv::imread() to load images, swap this to cv::COLOR_BGR2HSV (the old CV_ prefix is deprecated in modern OpenCV versions).
  • Optional Saturation Limit: If you only want desaturated blacks/grays (not dark colored pixels), adjust the upper saturation bound to match your threshold, like this:
    cv::Scalar upperBlack(255, threshold, threshold);
    
    This makes the filter behave more like your white filter, which restricts saturation to low values.

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

火山引擎 最新活动