Advertisement
Mat4297

Untitled

Sep 24th, 2024 (edited)
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 11.15 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import os
  4.  
  5.  
  6. def get_average_color(image: np.ndarray) -> np.ndarray:
  7.     """
  8.    Calculate the average color of an image.
  9.  
  10.    Parameters:
  11.    image (numpy.ndarray): The input image.
  12.  
  13.    Returns:
  14.    numpy.ndarray: The average color of the image.
  15.    """
  16.     average_color_per_row = np.average(image, axis=0)
  17.     average_color = np.average(average_color_per_row, axis=0)
  18.     return average_color
  19.  
  20.  
  21. def remove_outliers(data: list) -> list:
  22.     """
  23.    Remove outliers using the Interquartile Range (IQR) method.
  24.  
  25.    Parameters:
  26.    data (list): The input data.
  27.  
  28.    Returns:
  29.    list: The data with outliers removed.
  30.    """
  31.     q1, q3 = np.percentile(data, [25, 75])
  32.     iqr = q3 - q1
  33.     lower_bound = q1 - 1.5 * iqr
  34.     upper_bound = q3 + 1.5 * iqr
  35.     return [x for x in data if lower_bound <= x <= upper_bound]
  36.  
  37.  
  38. def get_color_limits_from_dataset(dataset_path: str) -> tuple:
  39.     """
  40.    Calculate color limits (HSV) based on a dataset of images, removing outliers.
  41.  
  42.    Parameters:
  43.    dataset_path (str): The path to the dataset of images.
  44.  
  45.    Returns:
  46.    tuple: The lower and upper color limits in HSV.
  47.    """
  48.     hues, saturations, values = [], [], []
  49.  
  50.     for filename in os.listdir(dataset_path):
  51.         if filename.endswith(".jpg") or filename.endswith(".png"):
  52.             image_path = os.path.join(dataset_path, filename)
  53.             image = cv2.imread(image_path)
  54.             hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  55.             average_color = get_average_color(hsv_image)
  56.             hues.append(average_color[0])  # Hue component
  57.             saturations.append(average_color[1])  # Saturation component
  58.             values.append(average_color[2])  # Value component
  59.  
  60.     # Remove outliers
  61.     hues = remove_outliers(hues)
  62.     saturations = remove_outliers(saturations)
  63.     values = remove_outliers(values)
  64.  
  65.     lower_limit = np.array([min(hues), min(saturations), min(values)], dtype=np.uint8)
  66.     upper_limit = np.array([max(hues), max(saturations), max(values)], dtype=np.uint8)
  67.  
  68.     return lower_limit, upper_limit
  69.  
  70.  
  71. def get_color_limits_from_hsv(
  72.     base_color: tuple,
  73.     hue_percentage: float,
  74.     saturation_percentage: float,
  75.     value_percentage: float,
  76. ) -> tuple:
  77.     """
  78.    Calculate color limits (HSV) based on a given color and user-provided percentages.
  79.  
  80.    Parameters:
  81.    base_color (tuple): The base color in HSV.
  82.    hue_percentage (float): The percentage range for hue.
  83.    saturation_percentage (float): The percentage range for saturation.
  84.    value_percentage (float): The percentage range for value.
  85.  
  86.    Returns:
  87.    tuple: The lower and upper color limits in HSV.
  88.    """
  89.     hue, saturation, value = base_color
  90.  
  91.     hue_range = 255 * hue_percentage / 100
  92.     saturation_range = 255 * saturation_percentage / 100
  93.     value_range = 255 * value_percentage / 100
  94.  
  95.     lower_limit = np.array(
  96.         [
  97.             max(0, hue - hue_range),
  98.             max(0, saturation - saturation_range),
  99.             max(0, value - value_range),
  100.         ],
  101.         dtype=np.uint8,
  102.     )
  103.     upper_limit = np.array(
  104.         [
  105.             min(255, hue + hue_range),
  106.             min(255, saturation + saturation_range),
  107.             min(255, value + value_range),
  108.         ],
  109.         dtype=np.uint8,
  110.     )
  111.  
  112.     return lower_limit, upper_limit
  113.  
  114.  
  115. def process_webcam_video(lower_limit: np.ndarray, upper_limit: np.ndarray):
  116.     """
  117.    Process video from the webcam to identify and highlight areas matching the color limits.
  118.  
  119.    Parameters:
  120.    lower_limit (numpy.ndarray): The lower HSV color limit.
  121.    upper_limit (numpy.ndarray): The upper HSV color limit.
  122.    """
  123.     cap = cv2.VideoCapture(0)
  124.  
  125.     while True:
  126.         ret, frame = cap.read()
  127.         if not ret:
  128.             break
  129.  
  130.         hsv_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
  131.  
  132.         # Create a mask based on color limits
  133.         mask = cv2.inRange(hsv_frame, lower_limit, upper_limit)
  134.  
  135.         # Find contours of areas that match the color range
  136.         contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  137.  
  138.         # Draw rectangles around each found contour
  139.         for contour in contours:
  140.             if cv2.contourArea(contour) > 500:  # Filter small contours
  141.                 x, y, w, h = cv2.boundingRect(contour)
  142.                 frame = cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 5)
  143.  
  144.         # Add color limit legend to the main frame
  145.         lower_color_bgr = cv2.cvtColor(np.uint8([[lower_limit]]), cv2.COLOR_HSV2BGR)[0][
  146.             0
  147.         ]
  148.         upper_color_bgr = cv2.cvtColor(np.uint8([[upper_limit]]), cv2.COLOR_HSV2BGR)[0][
  149.             0
  150.         ]
  151.  
  152.         cv2.rectangle(frame, (10, 10), (30, 30), lower_color_bgr.tolist(), -1)
  153.         cv2.putText(
  154.             frame,
  155.             "Lower Limit",
  156.             (35, 25),
  157.             cv2.FONT_HERSHEY_SIMPLEX,
  158.             0.5,
  159.             (255, 255, 255),
  160.             1,
  161.         )
  162.  
  163.         cv2.rectangle(frame, (10, 40), (30, 60), upper_color_bgr.tolist(), -1)
  164.         cv2.putText(
  165.             frame,
  166.             "Upper Limit",
  167.             (35, 55),
  168.             cv2.FONT_HERSHEY_SIMPLEX,
  169.             0.5,
  170.             (255, 255, 255),
  171.             1,
  172.         )
  173.  
  174.         # Add color limit legend to the mask
  175.         mask_with_legend = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)
  176.         cv2.rectangle(
  177.             mask_with_legend, (10, 10), (30, 30), lower_color_bgr.tolist(), -1
  178.         )
  179.         cv2.putText(
  180.             mask_with_legend,
  181.             "Lower Limit",
  182.             (35, 25),
  183.             cv2.FONT_HERSHEY_SIMPLEX,
  184.             0.5,
  185.             (255, 255, 255),
  186.             1,
  187.         )
  188.  
  189.         cv2.rectangle(
  190.             mask_with_legend, (10, 40), (30, 60), upper_color_bgr.tolist(), -1
  191.         )
  192.         cv2.putText(
  193.             mask_with_legend,
  194.             "Upper Limit",
  195.             (35, 55),
  196.             cv2.FONT_HERSHEY_SIMPLEX,
  197.             0.5,
  198.             (255, 255, 255),
  199.             1,
  200.         )
  201.  
  202.         # Show the frame and mask with legend
  203.         cv2.imshow("frame", frame)
  204.         cv2.imshow("mask", mask_with_legend)
  205.  
  206.         # Exit the loop by pressing 'q'
  207.         if cv2.waitKey(1) & 0xFF == ord("q"):
  208.             break
  209.  
  210.     # Release video capture and close all windows
  211.     cap.release()
  212.     cv2.destroyAllWindows()
  213.  
  214.  
  215. def identify_color_in_image(
  216.     image_path: str, lower_limit: np.ndarray, upper_limit: np.ndarray
  217. ):
  218.     """
  219.    Identify and highlight areas matching the color limits in an image.
  220.  
  221.    Parameters:
  222.    image_path (str): The path to the input image.
  223.    lower_limit (numpy.ndarray): The lower HSV color limit.
  224.    upper_limit (numpy.ndarray): The upper HSV color limit.
  225.    """
  226.     image = cv2.imread(image_path)
  227.     hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
  228.  
  229.     # Create a mask based on color limits
  230.     mask = cv2.inRange(hsv_image, lower_limit, upper_limit)
  231.  
  232.     # Find contours of areas that match the color range
  233.     contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
  234.  
  235.     # Draw rectangles around each found contour
  236.     for contour in contours:
  237.         if cv2.contourArea(contour) > 500:  # Filter small contours
  238.             x, y, w, h = cv2.boundingRect(contour)
  239.             image = cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 5)
  240.  
  241.     # Add color limit legend to the main image
  242.     lower_color_bgr = cv2.cvtColor(np.uint8([[lower_limit]]), cv2.COLOR_HSV2BGR)[0][0]
  243.     upper_color_bgr = cv2.cvtColor(np.uint8([[upper_limit]]), cv2.COLOR_HSV2BGR)[0][0]
  244.  
  245.     cv2.rectangle(image, (10, 10), (30, 30), lower_color_bgr.tolist(), -1)
  246.     cv2.putText(
  247.         image,
  248.         "Lower Limit",
  249.         (35, 25),
  250.         cv2.FONT_HERSHEY_SIMPLEX,
  251.         0.5,
  252.         (255, 255, 255),
  253.         1,
  254.     )
  255.  
  256.     cv2.rectangle(image, (10, 40), (30, 60), upper_color_bgr.tolist(), -1)
  257.     cv2.putText(
  258.         image,
  259.         "Upper Limit",
  260.         (35, 55),
  261.         cv2.FONT_HERSHEY_SIMPLEX,
  262.         0.5,
  263.         (255, 255, 255),
  264.         1,
  265.     )
  266.  
  267.     # Show the image with legend
  268.     cv2.imshow("image", image)
  269.     cv2.imshow("mask", mask)
  270.  
  271.     # Wait for a key press and close all windows
  272.     cv2.waitKey(0)
  273.     cv2.destroyAllWindows()
  274.  
  275.  
  276. if __name__ == "__main__":
  277.  
  278.     # Path to the dataset of images
  279.     # dataset_path = "path/to/your/dataset"
  280.     # Example usage
  281.     base_color = (30, 255, 255)  # Base HSV color (yellow)
  282.  
  283.     # Calculate color limits from the dataset
  284.     # lower_limit, upper_limit = get_color_limits_from_dataset(dataset_path)
  285.     lower_limit, upper_limit = get_color_limits_from_hsv(base_color, 3, 70, 70)
  286.     process_webcam_video(lower_limit, upper_limit)
  287.  
  288.  
  289.  
  290.  
  291.  
  292.  
  293.  
  294.  
  295.  
  296.  
  297.  
  298.  
  299.  
  300.  
  301.  
  302.  
  303.  
  304.  
  305.  
  306. import cv2
  307. import numpy as np
  308.  
  309.  
  310. # Function to select points on an image
  311. def select_points(event, x, y, flags, param):
  312.     if event == cv2.EVENT_LBUTTONDOWN:
  313.         points.append((x, y))
  314.         cv2.circle(img, (x, y), 5, (0, 255, 0), -1)
  315.         cv2.putText(
  316.             img,
  317.             f"Points: {len(points)}",
  318.             (10, 30),
  319.             cv2.FONT_HERSHEY_SIMPLEX,
  320.             1,
  321.             (255, 0, 0),
  322.             2,
  323.             cv2.LINE_AA,
  324.         )
  325.         cv2.imshow(window_name, img)
  326.  
  327.  
  328. # Load the images
  329. img1 = cv2.imread(
  330.     r"C:\Users\Admin\Documents\GitHub\PhotoColorAnalyzer\ITT\imageAlignment\test2.jpg"
  331. )
  332. img2 = cv2.imread(
  333.     r"C:\Users\Admin\Documents\GitHub\PhotoColorAnalyzer\ITT\imageAlignment\test2.jpg"
  334. )
  335.  
  336. # Check if images are loaded
  337. if img1 is None:
  338.     print("Error: Could not load image1.jpg")
  339.     exit()
  340. if img2 is None:
  341.     print("Error: Could not load image2.jpg")
  342.     exit()
  343.  
  344. # Create windows to display the images
  345. window_name = "Select 5 points in image 1"
  346. cv2.imshow(window_name, img1)
  347. points = []
  348. cv2.setMouseCallback(window_name, select_points)
  349. cv2.waitKey(0)
  350. points1 = points.copy()
  351.  
  352. # Mark the selected points on the first image
  353. for point in points1:
  354.     cv2.circle(img1, point, 5, (0, 0, 255), -1)
  355. cv2.putText(
  356.     img1,
  357.     f"Points: {len(points1)}",
  358.     (10, 30),
  359.     cv2.FONT_HERSHEY_SIMPLEX,
  360.     1,
  361.     (255, 0, 0),
  362.     2,
  363.     cv2.LINE_AA,
  364. )
  365. cv2.imshow(window_name, img1)
  366. cv2.waitKey(0)
  367.  
  368. window_name = "Select 5 points in image 2"
  369. cv2.imshow(window_name, img2)
  370. points = []
  371. cv2.setMouseCallback(window_name, select_points)
  372. cv2.waitKey(0)
  373. points2 = points.copy()
  374.  
  375. # Mark the selected points on the second image
  376. for point in points2:
  377.     cv2.circle(img2, point, 5, (0, 0, 255), -1)
  378. cv2.putText(
  379.     img2,
  380.     f"Points: {len(points2)}",
  381.     (10, 30),
  382.     cv2.FONT_HERSHEY_SIMPLEX,
  383.     1,
  384.     (255, 0, 0),
  385.     2,
  386.     cv2.LINE_AA,
  387. )
  388. cv2.imshow(window_name, img2)
  389. cv2.waitKey(0)
  390.  
  391. # Convert points to numpy arrays
  392. points1 = np.array(points1, dtype=np.float32)
  393. points2 = np.array(points2, dtype=np.float32)
  394.  
  395. # Compute the homography matrix
  396. H, _ = cv2.findHomography(points1, points2, cv2.RANSAC)
  397.  
  398. # Warp the first image to align with the second image
  399. aligned_img = cv2.warpPerspective(img1, H, (img2.shape[1], img2.shape[0]))
  400.  
  401. # Display the aligned image
  402. cv2.imshow("Aligned Image", aligned_img)
  403. cv2.waitKey(0)
  404. cv2.destroyAllWindows()
  405.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement