To detect whether an image is grayscale (i.e., contains only shades of gray) in Linux using HSV color space with a threshold, you can use Python and OpenCV. Here's how you can do it:
✅ Goal:
- Detect if an image is grayscale.
- Even if the image is in RGB format, determine whether it only uses grayscale colors.
- Use HSV color space and apply a threshold on saturation.
🧠 Explanation:
In HSV (Hue, Saturation, Value):
- Saturation represents the intensity of the color.
- A grayscale image will have low or zero saturation.
- So we check if all (or most) pixels have saturation below a given threshold.
🐍 Python Script Using OpenCV
import cv2
import numpy as np
import sys
def is_grayscale(image_path, saturation_threshold=10):
# Load image
image = cv2.imread(image_path)
if image is None:
raise FileNotFoundError(f"Unable to load image: {image_path}")
# Convert from BGR to HSV
hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV).astype("float32")
# Extract saturation channel
saturation = hsv_image[:, :, 1]
# Check percentage of pixels with saturation above threshold
non_gray_pixels = np.sum(saturation > saturation_threshold)
total_pixels = saturation.size
percent_color = (non_gray_pixels / total_pixels) * 100
return percent_color <= 1.0 # Adjust this threshold as needed
# Example usage
if __name__ == "__main__":
if len(sys.argv) < 2:
print("Usage: python detect_grayscale.py <image_path>")
sys.exit(1)
image_path = sys.argv[1]
try:
result = is_grayscale(image_path)
if result:
print(f"{image_path} is grayscale.")
else:
print(f"{image_path} is NOT grayscale.")
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
🛠️ How to Run
- Install dependencies:
pip install opencv-python numpy
-
Save the script as detect_grayscale.py.
-
Run it:
python detect_grayscale.py your_image.jpg
🔧 Parameters You Can Tune
saturation_threshold: Pixels with saturation above this value are considered "color".
% threshold: Max percentage of non-gray pixels allowed.
📌 Notes
- This method works for both JPEG and PNG files.
- It handles RGB images that are effectively grayscale.
- For performance, resize large images before processing if needed.
Let me know if you want a version in another language like Bash + ImageMagick, or a CLI-only tool!