Обнаружение объекта с OpenCVPython

Программы на Python
Anonymous
 Обнаружение объекта с OpenCV

Сообщение Anonymous »

Цель кода состояла в том, чтобы отобразить красные стрелки на следующем изображении + распечатать массив из них
В настоящее время мой код ищет объекты в определенном диапазоне красного цвета:
lower_red1 = [ 0, 120, 70]
overs_red1 = [10, 255, 255] < /p>
lower_red2 = [170, 120, 70]
overs_red2 = [180, 255, 255]
Код удается найти красные стрелки на дороге, но он также фиксирует другие красные объекты на экране. Дорога. < /p>
import cv2
import numpy as np

# Load the image
img = cv2.imread(r"C:\python_projects\macro\photos\games\west_city\west_city_map\above_leaf_vilige.png")

class DetectRoad:
@classmethod
def detect_red_arrows(cls):
# Convert the image to HSV color space for better color segmentation
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

# Define the range for red color in HSV (adjust these values based on your image)
lower_red1 = np.array([0, 120, 70])
upper_red1 = np.array([10, 255, 255])

lower_red2 = np.array([170, 120, 70])
upper_red2 = np.array([180, 255, 255])

# Create a mask for the red color (combining both red ranges)
mask1 = cv2.inRange(hsv, lower_red1, upper_red1)
mask2 = cv2.inRange(hsv, lower_red2, upper_red2)
mask = mask1 | mask2

# Apply the mask to the original image to extract the red arrows
red_arrows = cv2.bitwise_and(img, img, mask=mask)

# Convert to grayscale to apply edge detection
gray = cv2.cvtColor(red_arrows, cv2.COLOR_BGR2GRAY)

# Apply Gaussian blur to reduce noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Use Canny edge detection to detect edges in the red areas
edges = cv2.Canny(blurred, 50, 150)

# Perform morphological operations to close gaps in the road/path (optional)
kernel = np.ones((5, 5), np.uint8)
dilated = cv2.dilate(edges, kernel, iterations=1)

# Find contours in the edge-detected image
contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Initialize an image to display the results
output_img = img.copy()

# Lists to store x and y coordinates separately
x_coordinates = []
y_coordinates = []

# Iterate over contours to detect the red arrows and the road path
for c in contours:
# Approximate the contour to a polygon
epsilon = 0.04 * cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, epsilon, True)

# If the contour has 3 vertices (likely a triangle, i.e., an arrow)
if len(approx) == 3:
# Draw the red arrow in green
cv2.drawContours(output_img, [approx], -1, (0, 255, 0), 3)

# Store the coordinates of the arrow's vertices
for point in approx:
x_coordinates.append(int(point[0][0])) # Convert to plain int
y_coordinates.append(int(point[0][1])) # Convert to plain int

# Optionally: if the contour is part of a road path, you could also draw it
else:
# Draw non-arrow path in red
cv2.drawContours(output_img, [approx], -1, (0, 0, 255), 2)

# Store the coordinates of the road path points
for point in approx:
x_coordinates.append(int(point[0][0])) # Convert to plain int
y_coordinates.append(int(point[0][1])) # Convert to plain int

# Show the result
cv2.imshow("Detected Red Arrows and Path", output_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Print the stored coordinates as separate x and y values (now as plain integers)
print("Detected Coordinates (x positions):")
print(x_coordinates)
print("\nDetected Coordinates (y positions):")
print(y_coordinates)

@staticmethod
def run_process():
DetectRoad.detect_red_arrows()

DetectRoad.run_process()
< /code>
До сих пор я пытался обнаружить стрелки на пути на основе обнаружения красного цвета, но он не работал
Я ожидаю, что код обнаружит только красные стрелки, а не Другие красные объекты на экране

Подробнее здесь: https://stackoverflow.com/questions/793 ... ith-opencv

Вернуться в «Python»