From 0fb06b55e7f95549714bb0713d31a7cc70fee900 Mon Sep 17 00:00:00 2001 From: sonicboom989 <53375040+sonicboom989@users.noreply.github.com> Date: Sun, 30 Mar 2025 17:27:17 -0500 Subject: [PATCH] Create filtercolor.py Code for filtering color and produces an output with only the color ranges specified. --- filtercolor.py | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 filtercolor.py diff --git a/filtercolor.py b/filtercolor.py new file mode 100644 index 0000000..4a5ad88 --- /dev/null +++ b/filtercolor.py @@ -0,0 +1,38 @@ +import cv2 +import numpy as np +import os + +def filter_color(image_path, lower_bound, upper_bound, output_path=None): + # Read the image + image = cv2.imread(image_path) + if image is None: + raise FileNotFoundError(f"Could not read image from {image_path}") + + # Convert image from BGR to HSV color space + hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV) + + # Create a mask for the specified color range + mask = cv2.inRange(hsv_image, lower_bound, upper_bound) + + # Bitwise-AND mask and original image + result = cv2.bitwise_and(image, image, mask=mask) + + if output_path is None: + base, ext = os.path.splitext(image_path) + output_path = f"{base}_filtered{ext}" + + # Save the result image + cv2.imwrite(output_path, result) + print(f"Filtered image saved to {output_path}") + +# Example: Filter green color in HSV range + +def main(): + filename = 'KUbesat color filter\kubesattestpic.png' + lower_green = np.array([35, 40, 40]) # Lower bound of green in HSV + upper_green = np.array([85, 255, 255]) # Upper bound of green in HSV + + filter_color(filename, lower_green, upper_green) + +if __name__ == '__main__': + main()