VERYNICE.py
unknown
plain_text
a year ago
3.0 kB
6
Indexable
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image
image_path = r'C:\Users\Bernardo\Desktop\Project 4\Images\100rpm\5.png'
image = cv2.imread(image_path)
# Convert to grayscale for circle masking
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Detect the circular area using Hough Circle Transform
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, dp=1.2, minDist=100,
param1=50, param2=30, minRadius=50, maxRadius=200)
# If a circle is detected, create a mask
mask = np.zeros_like(gray)
if circles is not None:
circles = np.round(circles[0, :]).astype("int")
for (x, y, r) in circles:
cv2.circle(mask, (x, y), r, 255, thickness=-1)
# Apply the mask to isolate the circular area
masked_image = cv2.bitwise_and(image, image, mask=mask)
# Convert the masked image to HSV for color filtering
hsv = cv2.cvtColor(masked_image, cv2.COLOR_BGR2HSV)
# Define color ranges for filtering to capture lines, including red hues
# Yellow to green range
lower_yellow = np.array([20, 50, 50])
upper_yellow = np.array([90, 255, 255])
# Red ranges (since red wraps around the hue spectrum)
lower_red1 = np.array([0, 50, 50])
upper_red1 = np.array([10, 255, 255])
lower_red2 = np.array([170, 50, 50])
upper_red2 = np.array([180, 255, 255])
# Combine all masks
mask_yellow = cv2.inRange(hsv, lower_yellow, upper_yellow)
mask_red1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask_red2 = cv2.inRange(hsv, lower_red2, upper_red2)
# Final combined mask for colors
color_mask = cv2.bitwise_or(mask_yellow, mask_red1)
color_mask = cv2.bitwise_or(color_mask, mask_red2)
# Apply the combined mask to the masked image to isolate colored lines
colored_lines = cv2.bitwise_and(masked_image, masked_image, mask=color_mask)
# Convert the color-filtered image to grayscale for contour detection
colored_gray = cv2.cvtColor(colored_lines, cv2.COLOR_BGR2GRAY)
# Detect contours in the color-filtered grayscale image
contours, _ = cv2.findContours(colored_gray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# Create an output image to draw the detected contours and pink dots
output_with_dots = colored_lines.copy()
# Loop through each contour and place a pink dot at the center
for contour in contours:
# Calculate the center of each contour
M = cv2.moments(contour)
if M["m00"] != 0:
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])
# Draw a pink dot at the center of the contour
cv2.circle(output_with_dots, (cX, cY), radius=5, color=(255, 0, 255), thickness=-1)
# Display the result
plt.figure(figsize=(10, 10))
plt.subplot(1, 2, 1)
plt.imshow(cv2.cvtColor(colored_lines, cv2.COLOR_BGR2RGB))
plt.title("Isolated Colored Lines")
plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(output_with_dots, cv2.COLOR_BGR2RGB))
plt.title("Colored Lines with Pink Dots")
plt.show()
Editor is loading...
Leave a Comment